gpt4 book ai didi

c - 关于C中的FOPEN

转载 作者:行者123 更新时间:2023-11-30 15:21:14 25 4
gpt4 key购买 nike

我在 C 语言中遇到有关 FOPEN 的问题。

我有这段代码,可以从目录中读取特定文件

FILE *ifp ;
char directoryname[50];
char result[100];
char *rpath = "/home/kamal/samples/pipe26/divpipe0.f00001";
char *mode = "r";

ifp = fopen("director.in",mode); %director file contains path of directory

while (fscanf(ifp, "%s", directoname) != EOF)
{
strcpy(result,directoname); /* Path of diretory /home/kamal/samples/pipe26 */
strcat(result,"/"); /* front slash for path */
strcat(result,name); /* name of the file divpipe0.f00001*/
}

到目前为止,我的代码可以完美地创建一个看起来为“/home/kamal/samples/pipe26/divpipe0.f00001 ”的字符串。

当我尝试使用“结果”打开文件时出现问题,它给了我错误。相反,如果我使用“rpath”,即使两个字符串包含相同的信息,它也能正常工作。

 if (!(fp=fopen(rpath,"rb")))     /* This one works fine */
{
printf(fopen failure2!\n");
return;
}


if (!(fp=fopen(result,"rb"))) /* This does not work */
{
printf(fopen failure2!\n");
return;
}

有人可以告诉我为什么会收到此错误吗?

最佳答案

我认为你的意思是char result[100];;即没有星号。 (目录名也是如此。)

您当前正在堆栈分配一个包含 100 个指针的数组。这不会有好结果。

请注意,rpathmode 指向只读内存。实际上,您应该对这两个文字使用 const char* 。

关于c - 关于C中的FOPEN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29606233/

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