← The C Language Lesson 36 of 77 · 10 XP

Writing to a file

Theory and problem statement

Machine translation, not yet reviewed by a native speaker.

The writing functions are relatives of the screen output functions, just with a FILE * parameter:

fprintf(f, "Player: %s, score: %d\n", name, score);  // like printf
fputs("a line\n", f);                                // a string as it is
fputc('A', f);                                       // one character

In fact, printf(...) is fprintf(stdout, ...). stdout, stdin and stderr are three files that every program has open from the very start.

The "a" mode appends to the end without touching what's already there — that's how logs are written:

FILE *log = fopen("app.log", "a");
fprintf(log, "started\n");
fclose(log);

For binary data (pictures, your own formats) people use fwrite(ptr, size, count, f) and modes with the letter b: "wb", "rb".

Task. Read n and n numbers. Write the squares of these numbers to the file squares.txt, one per line. Then open the file, read it character by character and print all of its contents on the screen.

Sign up for free to solve this task right in your browser: code editor, running, test checks and hints.