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時,都會打印出文件的內容。fprintf不按我想要的方式運行
由於某些原因,在每一行中,變量「行」只是寫在自己身上。相反,我希望它不是打印輸出到一個文件中,然後在新行中打印出新行。我是否正確使用它?
示例:我使用的命令行參數yo.txt
傳遞給void fileOpen(char *fname)
。
在yo.txt
:
Hello stackoverflow.
#include "hi.txt"
Thank you!
在hi.txt
:
Please help me.
預期最終結果:
Hello stackoverflow.
Please help me
Thank you!
可能會在fprintf中添加''\ n''? – Kninnug
'perror(fname)','perror(fname)','perror(fname)'!!!!!如果我看到另一條錯誤消息,告訴我該消息適用的文件的名稱,我會尖叫。 –
您正在'w'模式下打開'output.txt'。每當你這樣做,你截斷(丟棄)以前寫的所有東西。 –