gpt4 book ai didi

c - fopen 的路径存储在变量中

转载 作者:行者123 更新时间:2023-11-30 19:01:49 25 4
gpt4 key购买 nike

我已将路径保存在文本文件中并希望将其读出。通过这些路径,我想读取新的文本文件,但如果我用变量调用 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 需要两个参数。来自 man: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 */

关于c - fopen 的路径存储在变量中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57179079/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com