The following example program must be executed with a command line argument representing the name of the text file we wish to read. The file must contain integers, separated by either a space or a newline. Reading will be halted when a nonnumeric value is encountered of the file has ended.
The program uses basic error checking – it validates the number of command line arguments, checks if the file opened successfully, checks the data it reads from the file. The example code is not able to distinguish between successfully reading until the end of the fileĀ or encountering an error reading it (e.g. file had an alphabetical character).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
/** * File: file_args.c * Author: Risto Heinsar * Created: 15.08.2022 * Modified: 20.08.2025 * * Description: Example on accepting the name of the input file * as the command line argument. Argument must be provided * when using the program. * Input file should contain integers only. * * Usage: ./program_name input_file_name */ #include <stdio.h> #include <stdlib.h> #define ARGS_COUNT 2 #define ARGS_EXEC_NAME argv[0] #define ARGS_FILENAME argv[1] void DisplayNumsInFile(const char *fName); int main(int argc, char *argv[]) { // Check that argument was provided if (argc != ARGS_COUNT) { printf("Usage %s <filename>\n", ARGS_EXEC_NAME); return EXIT_FAILURE; } DisplayNumsInFile(ARGS_FILENAME); return EXIT_SUCCESS; } void DisplayNumsInFile(const char *fName) { // Open the file pointed by the first argument FILE *fListOfNums = fopen(fName, "r"); if (fListOfNums == NULL) { printf("Error opening file \"%s\".\n", fName); exit(EXIT_FAILURE); } int number; int count = 1; // Loop through the file while (fscanf(fListOfNums, "%d", &number) == 1) { printf("%d. %d\n", count, number); count++; } printf("End of file or unexpected format reached!\n"); // Clean up fclose(fListOfNums); } |