read from text file in c
Here is an example of how to read from a text file in C:
Step 1: Include the necessary header files.
#include <stdio.h>
Step 2: Declare the file pointer variable.
FILE *file;
Step 3: Open the text file using the fopen()
function.
file = fopen("filename.txt", "r");
Note: Replace "filename.txt" with the name of your text file. The second argument "r" specifies that the file should be opened in read mode.
Step 4: Check if the file was successfully opened.
if (file == NULL) {
printf("Error opening the file.");
return 1;
}
Note: The fopen()
function returns NULL if it fails to open the file. In such cases, an error message is printed, and the program terminates.
Step 5: Read the contents of the file using the fscanf()
or fgets()
function in a loop.
char line[100]; // Assuming each line in the file is at most 100 characters long
while (fgets(line, sizeof(line), file) != NULL) {
// Process each line here
printf("%s", line); // Example: Print each line to the console
}
Note: The fgets()
function reads a line from the file and stores it in the line
variable. The loop continues until fgets()
returns NULL, indicating the end of the file.
Step 6: Close the file using the fclose()
function.
fclose(file);
Note: It is important to close the file after reading to free up system resources.
That's it! You have successfully read the contents of a text file in C. Remember to modify the code according to your specific requirements.