# include <stdio.h>
# include <string.h>
int main( )
{
int genericNumber;
FILE *fp = fopen("some_file.txt", "r");
if (fp == NULL)
{
printf("Unable to open file in reading mode. \n");
}
else
{
printf("Content: \n");
while (fscanf(fp, "%d", &genericNumber) == 1)
{
printf("Number: %d \n", genericNumber);
}
fclose(fp);
printf("Done. \n");
}
return 0;
}
This is a C program that reads a file named "some_file.txt" and prints out the content of the file if it contains integers. Here is a brief explanation of how the program works:
-
The program starts by declaring an integer variable named "genericNumber".
-
Then, it declares a pointer to a file named "fp" and uses the fopen() function to open the file "some_file.txt" in read mode.
-
If the file is not opened successfully (i.e., if fp is NULL), the program prints an error message.
-
If the file is opened successfully, the program enters a loop that reads the file using the fscanf() function. This function reads formatted input from a file, in this case, it reads an integer (%d) from the file and stores it in the "genericNumber" variable. The loop continues as long as fscanf() returns 1, which means that it has successfully read an integer from the file.
-
Inside the loop, the program prints the value of the "genericNumber" variable using printf().
-
After the loop finishes, the program closes the file using fclose().
-
Finally, the program prints a "Done" message and returns 0 to indicate that it has finished successfully.
Note that this program assumes that the file "some_file.txt" exists and contains integers separated by whitespace characters (e.g., spaces or newlines). If the file contains non-integer data or invalid input, the program may produce unexpected results.
No comments:
Post a Comment