I wrote a program which takes a file name as an argument, opens the file, parses its content and does some stuff. I am writing a test program that will test that program by executing it.
Here is my test class:
int main () {
FILE *input;
input = fopen("file.txt", "w+");
if (input == NULL) {
fprintf(stderr, "Unable to create a new file");
exit(1);
}
fprintf(input, "8\n");
if (execl("./a.out", "./a.out", "file.txt", NULL) == -1) {
fprintf(stderr, "Error forking program\n");
exit(1);
}
return 0;
}
When I open file.txt, I only see a blank file. My ./a.out program is giving out a parsing error (fgets is returning NULL) and I assume its because file.txt is not being written into. What’s the problem here? How can I debug such an issue? Why would fprintf ever not write into a file?
Thank you,
You need to flush the file — see fflush. On POSIX systems you can also use setbuf or setvbuf if you want to flush on every printf.
Edit: Actually, in your code, the appropriate thing to do is simply fclose the file before the execl; that of course flushes it. Also, you don’t need “w+”, and “input” isn’t a very good name for a file you’re writing to.
Additionally, you should name your programs appropriately rather than leaving them named a.out; execl of a.out is particularly dangerous as you don’t know which program is being run. If you were to compile the above program without a -o flag, it would overwrite a.out and invoking it would lead to recursive execution of itself, resulting in an infinite loop. Fortunately it would not flood your system with processes because you do not do a fork, contrary to your (erroneous) error message.
A nit: don’t forget to end your printfs with \n … the first one is lacking. Be particularly scrupulous about this in error messages, which don’t get thorough testing.