Text files: fopen, fgets and fprintf
Until now, everything your program knew disappeared when it ended. Files let you save data on disk and recover it on the next run, and they are essential for the final project, where you will save a contact book. In C you work with files through a FILE * pointer provided by the standard library (stdio.h). You already know it without realising: stdin, stdout and stderr are three FILE * opened automatically, and printf is just fprintf directed to stdout.
Open, check and close
fopen(name, mode) opens a file and returns a FILE *, or NULL on failure. The most used text modes are "r" to read (the file must exist), "w" to write (it creates the file or erases its previous content, careful) and "a" to append at the end without erasing. Always check the result of fopen: the file may not exist, the folder may lack permissions or the disk may be full. When it fails, perror("message") prints your message followed by the reason given by the system. When you finish, fclose releases the file and flushes pending data to disk; if you forget to close it, part of what you wrote may be lost.
#include <stdio.h>
int main(void) {
FILE *out = fopen("notes.txt", "w");
if (out == NULL) {
perror("fopen (write)");
return 1;
}
fprintf(out, "Ana;600123456\n");
fprintf(out, "Luis;611222333\n");
if (fclose(out) != 0) { /* fclose can fail when flushing */
perror("fclose");
return 1;
}
FILE *in = fopen("notes.txt", "r");
if (in == NULL) {
perror("fopen (read)");
return 1;
}
char line[100];
while (fgets(line, sizeof line, in) != NULL) {
printf("read: %s", line); /* line already ends with \n */
}
fclose(in);
return 0;
}
/* Output:
read: Ana;600123456
read: Luis;611222333
*/Reading line by line and parsing
fgets(buffer, size, file) reads at most size-1 characters or up to the end of the line, leaves the newline inside the buffer and always ends with '\0'. It returns NULL when no data remains, which is why it is used as the loop condition. Never use gets or while (!feof(f)): feof is only set after trying to read past the end, and the loop would process one extra line. To remove the final newline, the short and safe way is line[strcspn(line, "\n")] = '\0'. Then sscanf extracts the fields from the line just like scanf, but from a string; check that it returns the expected number of fields.
#include <stdio.h>
#include <string.h>
int main(void) {
FILE *in = fopen("notes.txt", "r"); /* created by the previous example */
if (in == NULL) {
perror("fopen");
return 1;
}
char line[100];
char name[50];
char phone[20];
int count = 0;
while (fgets(line, sizeof line, in) != NULL) {
line[strcspn(line, "\n")] = '\0';
/* %49[^;] reads up to 49 chars that are not ';' */
if (sscanf(line, "%49[^;];%19s", name, phone) == 2) {
printf("%s -> %s\n", name, phone);
count++;
} else {
fprintf(stderr, "skipping bad line: %s\n", line);
}
}
fclose(in);
printf("%d contacts loaded\n", count);
return 0;
}
/* Output:
Ana -> 600123456
Luis -> 611222333
2 contacts loaded
*/Notice the limit in the sscanf format (%49[^;] for a 50-element array and %19s for a 20-element one): it is the same safety rule you saw with scanf, always leave room for the '\0'. A common mistake is opening with "w" a file you wanted to keep: the previous content disappears instantly, without warning. If you want to add a contact without losing the others, use "a". Another mistake is a line longer than the buffer: fgets splits it into two reads and the second half will look like another line; choose a roomy buffer and, if it matters, check whether the last character is '\n'.
Binary files and position
Besides text, fwrite and fread copy blocks of bytes exactly as they are in memory: fwrite(&p, sizeof p, 1, f) saves a whole struct. It is fast and compact, but the file depends on the machine (type sizes, padding between fields), so it is not portable and cannot be read with an editor. For data the user may want to open or that must survive program changes, text is better. With fseek and ftell you move around the file and measure its size. Open binaries with "rb", "wb" or "ab": on Windows the b prevents newlines from being altered.
- fopen returns NULL on failure: check it and use perror.
- Modes: "r" read, "w" write (erases), "a" append.
- Read with fgets in a while (fgets(...) != NULL) loop.
- Remove the '\n' with strcspn and parse with sscanf (with limits).
- Always close with fclose.
اختبر ما تعلمته
السؤال 1 من 1What does fopen return if it cannot open the file?
✎ ملاحظاتي
محفوظ في هذا المتصفح فقط. سجّل الدخول لحفظه في حسابك.0/5000 حرف