C Program to read contents of a file

In C programming, there are several ways to read data from a file. These methods depend on the type of data stored in the file (text or binary) and the desired way of processing it.

Reading Text Line by Line

If the file contains lines of text, you can use fgets to read one line at a time.

char buffer[100]; FILE* file = fopen("textfile.txt", "r"); if (file == NULL) { perror("File opening failed"); return 1; } while (fgets(buffer, sizeof(buffer), file) != NULL) { printf("%s", buffer); // Process the line } fclose(file);

Reading Text Character by Character

To process text character by character, you can use fgetc.

int c; FILE* file = fopen("textfile.txt", "r"); if (file == NULL) { perror("File opening failed"); return 1; } while ((c = fgetc(file)) != EOF) { printf("%c", (char)c); // Process the character } fclose(file);

Reading Binary Data

If the file contains binary data, use fread to read binary data into a buffer.

int data[5]; FILE* file = fopen("binaryfile.bin", "rb"); if (file == NULL) { perror("File opening failed"); return 1; } fread(data, sizeof(int), 5, file); // Reads 5 integers into the 'data' array fclose(file);

Formatted Input (fscanf) for Text Files

If your text file has structured data, you can use fscanf to parse data based on a format specifier.

int age; char name[50]; FILE* file = fopen("data.txt", "r"); if (file == NULL) { perror("File opening failed"); return 1; } while (fscanf(file, "%s %d", name, &age) == 2) { printf("Name: %s, Age: %d\n", name, age); } fclose(file);

Custom Parsing for Text Files

You can also read and parse data from text files manually using string functions like fgets and then split and process the data accordingly.

char line[100]; FILE* file = fopen("data.txt", "r"); if (file == NULL) { perror("File opening failed"); return 1; } while (fgets(line, sizeof(line), file) != NULL) { // Custom parsing logic to extract and process data } fclose(file);

When working with file reading in C, it's essential to handle errors, check for the end of the file (using feof for text files), and properly close the file using fclose to release system resources.

Character-by-character VS. Line-by-line

The best way to read from a file depends on the specific needs of the program. If the program needs to process the data character-by-character, then character-by-character reading should be used. If the program needs to process the data line-by-line, then line-by-line reading should be used.

Conclusion

There are various ways to read data from a file. Common methods include reading text line by line using fgets, reading characters one at a time with fgetc, reading binary data using fread, and parsing formatted text data with fscanf. The choice of method depends on the type of data in the file and the desired processing approach.