我已将路径保存在文本文件中,并希望将其读出。使用这些路径,我想读取新的文本文件,但是如果我使用变量调用fopen(),则程序只会崩溃。 我保存的路径是绝对的。 我已经尝试读取不带变量的文件,这也起作用。
FILE *fp;
FILE *variable;
char file[256];
fp = fopen("C:\\Example\\Example.txt","r");
if(fp != NULL)
{
while(fgets(file, 256, fp) != NULL)
{
variable = fopen(("%s", file), "r");
// another while loop which reads out the content of the variablefile
fclose(variable);
}
fclose(fp);
}
答案 0 :(得分:1)
您的代码中有两个问题。首先是这一行
variable = fopen(("%s", file), "r");
我不知道您在哪里找到了这个符号,但是fopen需要两个参数。来自人:FILE *fopen(const char *pathname, const char *mode)
。基本上是两个字符串,一个用于路径,另一个用于打开模式,因此正确调用fopen将是:
variable = fopen(file, "r");
另外,fgets将读取的所有换行符存储到缓冲区中。只需在打开文件之前删除此换行符即可:
char *newline = strchr(Name, '\n');
if (newline)
/*if a newline is found, we remove it*/
*pos = '\0';
else
/*error: input too long for buffer */