tags:

views:

106

answers:

3

i have an char array b[20] which i want to write into a file . After every iteration the value of b[20] changes , so i would like to write the string in each line of the file in each iteration . So how can i change a new line in a file and also put in a array of character?

+3  A: 

Assuming the char array contains a null-terminated string:

fprintf(file, "%.20s\n", b);
Marcelo Cantos
+6  A: 

Something like:

FILE *fp = fopen("file.txt","w");
// check for error
char b[20];

while(some_condition) {

 // populate the char array b and terminate it with NULL char.

 // write to file...and write a newline.
 fprintf(fp,"%s\n",b); 
}
codaddict
use FILE *fp = fopen("file.txt","a"); instead of "w". In append mode the contents are automatically added to the end of the file...
CVS-2600Hertz
@CVS That depends on if that's what the OP wants to do. He clearly wants to append on each iteration (which happens in either case), but it's not clear that he doesn't want to clear the file and start afresh each time he runs the program (as happens with "w", but not with "a", as you noted).
Tyler McHenry
Also, don't forget the `fclose(fp)` after the loop
Tyler McHenry
Did this not fix the issue ?
codaddict
A: 

Easy way:

int main() {
   freopen ( "output.txt", "w", stdout );
   printf ( "Hello!\n" );
   puts ( "World!\n" );
   ...
}

and all standart output is written to "output.txt"

gmunkhbaatarmn
I wouldn't alter the state of stdout.
Andrei Ciobanu