C program file reading
example c program to read text and numerical data from non-binary file
Here’s a basic example in C for reading text and numerical data from a text file. This program assumes
the file contains lines with a string (text data) and an integer (numerical data) in each line. It reads these
values line-by-line until it reaches the end of the file.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("data.txt", "r"); // Open file for reading
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
char text[100];
int number;
// Reading each line with a string and an integer
while (fscanf(file, "%99s %d", text, &number) == 2) {
printf("Text: %s, Number: %d\n", text, number);
}
fclose(file); // Close the file
return EXIT_SUCCESS;
}
Explanation
1. File Open: `fopen("data.txt", "r")` opens the file in read mode. Replace `"data.txt"` with the
path of your file.
2. Data Format: `fscanf(file, "%99s %d", text, &number)` reads a string (`%s`) and an integer (`%d`)
from each line. The `99` ensures the string buffer `text` is safe from overflow.
3. Loop: The `while` loop continues until it can't read a valid string-integer pair.
4. File Close: Always close the file after reading to free resources.
Sample `data.txt`
hello 42
world 99
example 123
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 1/3
Each line should match the format specified in `fscanf`, or the program may not work as expected.
what is perror
The `perror` function in C is used to display an error message associated with the most recent error that
occurred during a standard library or system call. It’s particularly useful for reporting file I/O errors,
memory allocation errors, and other issues where the operating system sets an error code.
Syntax
void perror(const char *message);
How it Works
`perror` takes a string `message` as an argument.
It prints the `message` followed by a colon (`:`) and the error message corresponding to the
current value of the global variable `errno`.
`errno` is set automatically by system or library calls when they encounter errors, so `perror` can
output the specific reason for the error.
Example Usage
In the previous code, if `fopen` fails (e.g., if the file doesn’t exist or cannot be opened), `perror("Error
opening file")` will print a message like:
yaml
Error opening file: No such file or directory
This message provides context (`Error opening file`) followed by a more specific system error message
(`No such file or directory`).
When to Use `perror`
Use `perror` when you want to debug or provide users with details about why an operation failed,
especially in file handling, memory allocation, or other system-level operations.
repeat code example for reading 3 doubles
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 2/3
Here’s a modified example to read three `double` values from each line in a text file.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *file = fopen("data.txt", "r"); // Open file for reading
if (file == NULL) {
perror("Error opening file");
return EXIT_FAILURE;
}
double num1, num2, num3;
// Reading each line with three double values
while (fscanf(file, "%lf %lf %lf", &num1, &num2, &num3) == 3) {
printf("Numbers: %.2f, %.2f, %.2f\n", num1, num2, num3);
}
fclose(file); // Close the file
return EXIT_SUCCESS;
}
Explanation
1. File Open: `fopen("data.txt", "r")` opens the file in read mode. Replace `"data.txt"` with your
file path.
2. Data Format: `fscanf(file, "%lf %lf %lf", &num1, &num2, &num3)` reads three `double` values.
The `%lf` format specifier is used for reading `double` values in `fscanf`.
3. Loop: The `while` loop continues as long as it successfully reads three `double` values from each
line.
4. Printing: The `printf` statement displays the values, formatted to two decimal places.
5. File Close: Always close the file after reading.
Sample `data.txt`
1.23 4.56 7.89
2.34 5.67 8.90
3.45 6.78 9.01
Each line should contain three `double` values separated by spaces, matching the `fscanf` format.
Printed using Save ChatGPT as PDF, powered by PDFCrowd HTML to PDF API. 3/3