Summing the numbers in a file
The file date.txt holds integers separated by spaces and newlines. Print how many numbers there are and their sum.
1 2 3
4 55 15Data in memory disappears when the program ends. Files are data structures organized on external storage, which allow information to be kept between runs and exchanged between applications.
| Criterion | Categories | Description |
|---|---|---|
| By content | text files | characters organized in lines; end of line marked by <CR><LF> |
| typed files | records of a certain type, elementary or structured | |
| untyped files | binary files, raw sequences of bytes | |
| By access | sequential access | information is processed only in record order |
| direct access | components can be processed in any order, after positioning | |
| By operations | input | reading only |
| output | writing only | |
| input/output | both - information can be updated |
Every transfer is preceded by the opening operation, which creates a stream and
associates it with the file. A variable of type FILE * is used, and a buffer zone
through which the transfers happen is allocated automatically.
FILE *f = fopen("data.txt", "r"); // 1. opening
if (f == NULL) { // 2. mandatory CHECK
printf("Cannot open the file!\n");
return 1;
}
/* ... reading or writing ... */ // 3. processing
fclose(f); // 4. closing
fclose. If the program ends without closing,
the last data written can be lost. In addition, the number of files open at once is limited.| Function | Role |
|---|---|
fopen(name, mode) | opens the file; returns NULL on failure |
fclose(f) | flushes the buffer and closes the file |
feof(f) | tests whether the end of the file has been reached |
ferror(f) | tests whether an error has occurred |
fflush(f) | forces the buffer to be written to disk |
remove(name) | deletes the file |
rename(old, new) | renames the file |
| Mode | Meaning | If the file exists | If it does not exist |
|---|---|---|---|
"r" | reading | opened from the start | error (NULL) |
"w" | writing | all contents are erased! | created |
"a" | appending | writing happens at the end | created |
"r+" | reading and writing | opened from the start | error |
"w+" | reading and writing | all contents are erased | created |
"a+" | reading and appending | writing happens at the end | created |
The letter b is added for binary files ("rb", "wb",
"ab") and t for text, which is the default mode.
"w" instantly erases all of its contents, even if nothing is written afterward. To
append to an existing file, use "a".| Level | Reading | Writing |
|---|---|---|
| Character | fgetc(f), getc(f) | fputc(c, f), putc(c, f) |
| Line / string | fgets(s, n, f) | fputs(s, f) |
| Formatted | fscanf(f, "...", ...) | fprintf(f, "...", ...) |
fprintf ↔ printf, fscanf ↔
scanf, fgets ↔ gets. The difference is the first
parameter, which indicates the stream. printf(...) is equivalent to
fprintf(stdout, ...).feof function becomes true only
after a failed read, not before. The loop
while (!feof(f)) { fscanf(...); ... } processes the last record twice. Correct:
while (fscanf(f, "%d", &x) == 1) { ... }size_t fread (void *p, size_t size, size_t nr, FILE *f); size_t fwrite(const void *p, size_t size, size_t nr, FILE *f); // p - the address of the memory zone // size - the size of one record, in bytes // nr - how many records are transferred // f - the stream // returns the number of records actually transferred
| Aspect | Text file | Binary file |
|---|---|---|
| Content | readable characters | exact copy of the in-memory representation |
| The number 12345 | 5 characters (5 bytes) | 4 bytes (an int) |
| Manual editing | possible in any editor | practically impossible |
| Speed | slower (conversions) | fast, no conversions |
| Portability | good | limited (endianness, padding) |
| Function | Role |
|---|---|
fseek(f, offset, origin) | moves the position indicator |
ftell(f) | returns the current position, in bytes |
rewind(f) | returns to the start of the file |
| Origin constant | Reference point |
|---|---|
SEEK_SET | the start of the file |
SEEK_CUR | the current position |
SEEK_END | the end of the file |
fseek(f, n * sizeof(Record), SEEK_SET); followed by fread(...). This is
the major advantage of binary files with fixed-size records: any element is accessed directly,
with no need to scan the whole file.
#include <stdio.h>
int main(void)
{
FILE *f = fopen("data.txt", "w"); // WARNING: erases existing contents
if (f == NULL) {
printf("Cannot create the file!\n");
return 1;
}
fprintf(f, "John Smith;20;9.15\n");
fprintf(f, "Mary Johnson;21;8.70\n");
fprintf(f, "Radu Georgescu;20;9.60\n");
fclose(f);
printf("File created.\n");
// appending at the end, without erasing the contents
f = fopen("data.txt", "a");
if (f) {
fprintf(f, "Ana Dumitrescu;22;9.85\n");
fclose(f);
printf("Record added.\n");
}
return 0;
}
#include <stdio.h>
int main(void)
{
FILE *f = fopen("data.txt", "r");
if (f == NULL) {
printf("The file does not exist!\n");
return 1;
}
char line[200];
int nrLines = 0;
// correct version: the condition is precisely the success of the read
while (fgets(line, sizeof(line), f) != NULL) {
nrLines++;
printf("%3d: %s", nrLines, line);
}
printf("\nTotal %d lines\n", nrLines);
fclose(f);
// formatted reading, field by field
f = fopen("data.txt", "r");
char name[50];
int age;
float average;
printf("\nStructured reading:\n");
while (fscanf(f, "%49[^;];%d;%f\n", name, &age, &average) == 3) {
printf(" %-20s %3d years average %.2f\n", name, age, average);
}
fclose(f);
return 0;
}
#include <stdio.h>
typedef struct {
char name[50];
int age;
float average;
} Student;
int main(void)
{
Student group[3] = {
{"John Smith", 20, 9.15f},
{"Mary Johnson", 21, 8.70f},
{"Radu Georgescu",20, 9.60f}
};
// binary write: the whole array, in a single call
FILE *f = fopen("students.dat", "wb");
if (!f) return 1;
fwrite(group, sizeof(Student), 3, f);
fclose(f);
// reading record number 1 (the second one), WITHOUT reading the first
f = fopen("students.dat", "rb");
if (!f) return 1;
Student one;
fseek(f, 1 * sizeof(Student), SEEK_SET); // direct positioning
fread(&one, sizeof(Student), 1, f);
printf("Record 1: %s, %d years, average %.2f\n",
one.name, one.age, one.average);
// the size of the file
fseek(f, 0, SEEK_END);
long size = ftell(f);
printf("File size: %ld bytes = %ld records\n",
size, size / (long)sizeof(Student));
fclose(f);
return 0;
}
#include <stdio.h>
int main(void)
{
FILE *source = fopen("data.txt", "rb");
if (!source) { printf("The source is missing\n"); return 1; }
FILE *dest = fopen("copy.txt", "wb");
if (!dest) { fclose(source); return 1; }
char buffer[1024];
size_t bytesRead;
long total = 0;
// copying in blocks, much faster than byte by byte
while ((bytesRead = fread(buffer, 1, sizeof(buffer), source)) > 0) {
fwrite(buffer, 1, bytesRead, dest);
total += bytesRead;
}
printf("Copied %ld bytes\n", total);
fclose(source);
fclose(dest);
return 0;
}
The boxes below have their own file system, which exists only on the page. Files written by one program can be read right afterward by the same program.
"w" to "a"
(append) and run twice: you will see the lines being added at the end instead of replacing the
file.story.txt already exists in this box's
file system.This is where you write the code. The ✓ Check button runs your program on several data sets and shows you right away where the result differs. At the end you submit the track you chose, and the instructor grades it automatically.
Every exercise has the program already started, and the comments tell you what is left to add. Write the code, press ✓ Check and read what each failed test says. If you get stuck, open the hints one at a time. You may also print messages for the user (such as Enter n:); the test looks at what you print at the end.
The file date.txt holds integers separated by spaces and newlines. Print how many numbers there are and their sum.
1 2 3
4 55 15The file text.txt holds a text (each line has at most 200 characters). Print the number of lines and the longest line (without '\n'); on a tie, the first one.
Ana are mere
Ion
programarea calculatoarelor3
programarea calculatoarelorRead n from the keyboard. Write the squares of the numbers from 1 to n into the file patrate.txt, one per line. Close the file, reopen it for reading and print the sum of the values read from it.
314Open note.txt, which holds integer grades. If the file does not exist, print cannot open file. Otherwise print the highest grade (the file holds at least one grade).
7 9 49The file jurnal.txt already has a few lines. Read a new line (a single word) from the keyboard, append it to the end of the file without losing what was there, then read the file again and print the number of lines and the last line.
intrare3intrare1
intrare23 intrare3Problems start from an empty main. The output format must be followed exactly (spaces and newlines do not matter unless the statement says otherwise), so do not print prompts. The visible tests cover only the simple cases; grading also runs hidden tests chosen to catch the edge cases.
For the file text.txt, print the number of lines, words and characters, like the wc program: lines are the '\n' characters, words are sequences of characters other than space, TAB and '\n', and every character is counted.
Ana are mere
si pere2 5 21The file studenti.txt holds on each line Name;grade1;grade2;grade3 (the name may contain spaces, the grades are integers). For every student with an average of at least 5, print Name: average (the average with two decimals), in file order, then, on the last line, the number of students who failed.
Popescu Ana;9;8;10
Ionescu Dan;4;5;4Popescu Ana: 9.00
1Read n records code price (integer, real) from the keyboard and write them with fwrite into the binary file produse.bin. Then read an index k (from 0), reopen the file, jump straight to record k with fseek, read it with fread and print code price (the price with two decimals). If record k does not exist, print missing.
3
10 2.5
20 3.75
30 9
120 3.75The files a.txt and b.txt hold integers sorted in ascending order. Write every number into c.txt, merged (still ascending, one per line), then read c.txt back and print its contents on one line.
1 4 92 3 10 111 2 3 4 9 10 11"w" and observe what happens to its contents."a", without losing the old data.while (!feof(f)) and while (fscanf(...) == n).fseek and rewriting in place, without recreating the file), and logical deletion
through an indicator field. Add a "compaction" function that physically removes the records
marked as deleted.