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?
views:
106answers:
3
+3
A:
Assuming the char array contains a null-terminated string:
fprintf(file, "%.20s\n", b);
Marcelo Cantos
2010-04-18 13:25:34
+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
2010-04-18 13:27:01
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
2010-04-18 13:33:52
@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
2010-04-18 13:36:41
Also, don't forget the `fclose(fp)` after the loop
Tyler McHenry
2010-04-18 13:37:11
Did this not fix the issue ?
codaddict
2010-04-20 11:16:27
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
2010-04-18 15:24:00