Currently I have the argc, argv and temp pieces placed in to be passed, and when I compile it returns no errors, but when I call the function later in the program and pass it a char array. It returns a stack dump. From what I have learned so far arrays cannot be passed back from a function and that is why I have passed the pointers.
int In2File(int argc, char *argv[], char *temp[] ){
if (argc == 2) { //open file
FILE *user_file;
user_file = fopen(argv[1], "r");
if (user_file == NULL) {
printf("No data was found.\nEnd(Error 1)");
exit(2);
}
else {
int g = 0;//temp counter to load
char c = 0;
while ((c = fgetc(user_file)) != EOF && g <= tmplng - 1) { //Used Fgetc instead of fgets because Fgetc allows me to read
*temp[g] = c; //until the end of the file and read each character. Even if there is an \n character.
g++; // The second g < tmplng-1 is used to make sure that the \0 can be placed into the array.
}
printf("%s\n", temp);
fclose(user_file);//Closed the txt file that was loaded by user in args(1)
printf("\nFile Loaded.\n");
}
}
else if (argc > 2) { // Will exit if arguments are greater than 2.
printf("Format: %s 'filename'", argv[0]);
exit(1);
}
else {
printf("File not provided. Enter information:\n");//If the user doesnt provide a file allow manual input.
fgets(*temp, tmplng, stdin);
}
}
In2File(argc,argv,temp);
Anyone have an idea as to where I went wrong with this function? I read a few similar posts but they were for C++ and Python. Which I havent learned C++ as yet and python is different to this beast called C.
Edit:
const int tmplng = 1000; //The only variables needed
char temp[tmplng]; //
char temp2[tmplng]; //
printf("Starting....\n"); //Used for testing debugging.
elsestatements which clutter it. For example afterexit(2);there is no possibleelse.const int tmplng = 1000;means thatchar temp[tmplng];is a VLA (variable length array). C++ has different rules, but in C, it's a VLA. It doesn't hurt anything — you should just be aware.