How can I read a file in C?
- User
How can I read a file in C?
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
How can I read a file in C?
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
To read a file in C, follow these steps using standard library functions from <stdio.h>:
#include <stdio.h>.fopen() with mode "r" (text) or "rb" (binary).NULL on failure).fscanf(), fgets(), or fread().fclose() to release resources.#include <stdio.h>
int main() {
FILE *file = fopen("data.txt", "r");
if (!file) {
perror("Error");
return 1;
}
int num;
while (fscanf(file, "%d", &num) == 1) {
printf("Read integer: %d\n", num);
}
fclose(file);
return 0;
}
#include <stdio.h>
int main() {
FILE *file = fopen("text.txt", "r");
if (!file) {
perror("Error");
return 1;
}
char line[256];
while (fgets(line, sizeof(line), file)) {
printf("Read line: %s", line);
}
fclose(file);
return 0;
}
#include <stdio.h>
typedef struct {
int id;
char name[50];
} Student;
int main() {
FILE *file = fopen("students.bin", "rb");
if (!file) {
perror("Error");
return 1;
}
Student student;
while (fread(&student, sizeof(Student), 1, file) == 1) {
printf("ID: %d, Name: %s\n", student.id, student.name);
}
fclose(file);
return 0;
}
"r" for text, "rb" for binary.fopen() returns NULL (e.g., file not found).fscanf() returns the number of successfully read items.fgets() returns NULL on EOF/error.fread() returns the number of items read.char line[256]) are large enough to prevent overflow.| Function | Use Case | Example |
|---|---|---|
fscanf() | Read formatted data (e.g., %d, %s) | fscanf(file, "%d", &num) |
fgets() | Read a line of text | fgets(buffer, size, file) |
fread() | Read binary data | fread(&struct, sizeof(...), 1, file) |
For more details, refer to the C Standard Library documentation.