f8.cpp
1 /* 2 * FILE : f8.cpp 3 * PROJECT : SENG1000 - FOCUSED ASSIGNMENT 8 4 * PROGRAMMER : Tian Yang 5 * FIRST VERSION : 2024-03-19 6 * DESCRIPTION : 7 * This program practice at working with C-style strings, files, command-line arguments, and structs. 8 */ 9 10 #pragma warning(disable: 4996) 11 12 #include <stdio.h> 13 #include <string.h> 14 #include <stdlib.h> 15 16 #define MAXLENGTH 41 // 20(directory) + 20(filename) + 1(terminator) 17 18 typedef struct 19 { 20 int howMany; 21 const char* theText; 22 const char* directoryPath; 23 const char* filename; 24 } MyDat; 25 26 int main(int argc, char* argv[]) 27 { 28 if(argc != 5) 29 { 30 printf("Error: Incorrect number of arguments.\n"); 31 return 1; 32 } 33 MyDat myArgs = { 34 .howMany = strtol(argv[1], NULL, 10), 35 .theText = argv[2], 36 .directoryPath = argv[3], 37 .filename = argv[4]}; 38 39 char filename[MAXLENGTH] = ""; 40 strcpy(filename, myArgs.directoryPath); 41 strcat(filename, "\\"); 42 FILE* file = fopen(strcat(filename, myArgs.filename), "w"); 43 if(file == NULL) 44 { 45 printf("Can't open or create %s\n", filename); 46 return 0; 47 } 48 for (int i = 0; i < myArgs.howMany; i++) 49 { 50 if(fprintf(file, "%s\n", myArgs.theText) < 0) 51 { 52 printf("Can't write to %s\n", filename); 53 break; 54 } 55 } 56 if(fclose(file)) 57 { 58 printf("Can't close %s\n", filename); 59 } 60 61 return 0; 62 }