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();
}
程序的要点是递归文件提取。每次它在行的开头看到#include 时,它都会打印出文件的内容。
出于某种原因,在每一行中,变量“line”只是覆盖了自身。相反,我希望它而不是打印输出到文件.. 然后在新行中打印出新行。我使用正确吗?
示例:我使用传递给 void fileOpen(char *fname)
的命令行参数 yo.txt
。
在 yo.txt
中:
Hello stackoverflow.
#include "hi.txt"
Thank you!
在hi.txt
中:
Please help me.
预期的最终结果:
Hello stackoverflow.
Please help me
Thank you!
最佳答案
当您进入下一个级别时,即
strcpy(fileName, extractSubstring(line));
fileOpen(fileName);
你再次打开相同的输出文件,
newTxt = fopen("output.txt", "w");
而是将文件指针作为函数参数传递给 fileOpen。在打开第一个文件之前,您应该打开输出文件并将其传递给 fileOpen。
void fileOpen(char * fname, FILE* output)
关于c - fprintf 没有按照我想要的方式工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19566296/