The following example program takes the name of the input file as a command line argument.
Input file should contain integers, separated by either a space or a newline. Reading of the input file is halted if a non-numeric value is found or the end of the file is reached.
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 |
/** * File: file_args.c * Author: Risto Heinsar * Created: 15.08.2022 * * 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 ARG_COUNT 2 #define ARG_POS_EXEC 0 #define ARG_POS_FILENAME 1 void DisplayNumsInFile(FILE *fp); int main(int argc, char *argv[]) { // Check that argument was provided if (argc != ARG_COUNT) { printf("Usage %s file.\n", argv[ARG_POS_EXEC]); return EXIT_FAILURE; } // Open the file FILE *fp = fopen(argv[ARG_POS_FILENAME], "r"); if (fp == NULL) { printf("Error opening file \"%s\".\n", argv[ARG_POS_FILENAME]); return EXIT_FAILURE; } DisplayNumsInFile(fp); // Clean up fclose(fp); return EXIT_SUCCESS; } void DisplayNumsInFile(FILE *fp) { int temp; int i = 1; // Loop through the file while (fscanf(fp, "%d", &temp) == 1) { printf("%d. %d\n", i, temp); } printf("End of file or unexpected format reached!\n"); } |