# [SOLVED]writing to a text file

Status
Not open for further replies.

#### dayana42200

##### Junior Member level 3
Dear all,

How can I write the displayed output in the command prompt to a text file?

Code:
#include<stdio.h>
#include<string.h>
int main()
{
/*declare and initialise variable*/
char message[32][114],buffer[114];
int i=1;
FILE *file_in;
FILE *file_out;

file_in=fopen("exon11.txt", "r");
file_out=fopen("1.txt", "w");

/*stores and prints the data from the string*/
while(fgets(buffer,114,file_in))
{
strcpy(message[i],buffer);
fputs(message[i],file_out);
printf(">%d\n%s\n",i,message[i]);
i++;
}

getchar();
return 0;

}

tq very much.

% cat > hoge.txt

Ctrl-c

#### betwixt

##### Super Moderator
Staff member
How can I write the displayed output in the command prompt to a text file?

The command prompt comes from the OS that executes your program, not the program itself. If you want to save the result of the printf() command to a file (capture the text output) just add "> MyFile" to the end of the line that starts your program. "MyFile" can be any valid file name, including a path if needed.

For example, if "MyProgram" produced the text "Hello World", typing this:
MyProgram > result.txt
would produce a file called "result.txt" with "Hello World" in it.
If you want to add to an existing file rather than create a new one, use >> instead of >. If the file doesn't exist, it will create it then add to it.

Brian.

#### dayana42200

##### Junior Member level 3
I am sorry. I do not understand. Can you give some example where can I put the suggested command?

#### dayana42200

##### Junior Member level 3
Can this command is used in code block? Im using window 10

Last edited:

#### betwixt

##### Super Moderator
Staff member
dayana42200, are you trying to write the text file from inside the program or are you trying to capture the output to screen into a text file?

Put another way, when the printf() in your program sends text to the screen, are you trying to save it to a file as well, from inside the program or are you trying to save the characters that you see displayed via the screen? The first method is a simple file open/write/close in your code, the second requires the operating system to redirect or duplicate (tee) screen output to a file so it is done at OS level from outside your program.

Brian.

#### dayana42200

##### Junior Member level 3
ok its working. I at fclose() command. Thank you for all the helps. Can you guys explain to me, why the data is written in the text file when fclose() command is used?

Status
Not open for further replies.