路径存储在变量中的 fopen

fopen with path stored in variable

我已将路径保存在文本文件中,想读出它们。使用这些路径我想读取新的文本文件,但是如果我用变量调用 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);
}

您的代码中有两个问题。首先是这一行

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 = '[=12=]';
else
    /*error: input too long for buffer */