Järgnev programm tuleb käivitada koos käsureaargumendiga, milleks on tekstifaili nimi. Fail peab koosnema täisarvudest, mis on eraldatud tühiku või reavahetusega. Sisendfaili lugemine katkestatakse mittenumbrilise väärtuse leidmisel või faili lõppu jõudes.
Rakendus kasutab lihtsaid veakontrolle – käsurea argumentide arvu kontrollimine, faili avamise kontroll, failist loetava sisendi kontroll. Küll aga ei ole näiterakendus võimeline aru saama, kas fail loeti edukalt lõpuni või tekkis lugemisel viga (nt loeti failist mõni tähemärk).
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); } |