Reputation: 4185
void fileOpen(char * fname)
{
FILE *txt, *newTxt;
char line[256];
char fileName[256];
txt = fopen(fname, "r");
if(txt == NULL)
{
perror("Error opening file");
exit (EXIT_FAILURE);
}
newTxt = fopen("output.txt", "w");
if(newTxt == NULL)
{
perror("Error opening file");
exit(EXIT_FAILURE);
}
//Problem is in the while loop
while(fgets(line, 256, txt) != NULL)
{
if (strncmp(line, "#include", 7) == 0)
{
strcpy(fileName, extractSubstring(line));
fileOpen(fileName);
}
else
fprintf(newTxt, "%s", line); <---- It just prints over itself
}
fcloseall();
}
The point of the program is recursive file extraction. Every time it sees #include at the start of the line, it prints out the contents of the file.
For some reason in every line, the variable "line" just writes over itself. Instead, I want it to rather than printout to a file.. then in a new line printing out the new line. Am I using it correctly?
Example: I use a command line argument yo.txt
which is passed to void fileOpen(char *fname)
.
In yo.txt
:
Hello stackoverflow.
#include "hi.txt"
Thank you!
In hi.txt
:
Please help me.
Expected final result:
Hello stackoverflow.
Please help me
Thank you!
Upvotes: 0
Views: 108
Reputation: 36092
When you move to the next level i.e.
strcpy(fileName, extractSubstring(line));
fileOpen(fileName);
you open the same output file again,
newTxt = fopen("output.txt", "w");
Instead pass the file pointer to the output file as a function argument to fileOpen. Before you open the first file you should open the output file and pass it to fileOpen.
void fileOpen(char * fname, FILE* output)
Upvotes: 3