gpt4 book ai didi

c - 这些字符串是否为 fopen() 正确连接?

转载 作者:太空宇宙 更新时间:2023-11-04 04:35:05 24 4
gpt4 key购买 nike

我想连接两个字符串 config_pathconfig_file 并将该字符串传递给 fopen()。问题是 fopen() 返回一个错误,即使我 100% 文件存在。事实上,我在将字符串传递到 fopen() 之前在命令行中打印该字符串,如果我将此字符串直接复制到我的源代码中,那么 fopen() 找到文件。这里有什么问题?

命令行输出

config: /nfs/stak/students/m/morriluk/.myshellrc|header: HOME
Unable to open configuration file: No such file or directory

源代码

  1 #define _POSIX_C_SOURCE 200908L
2 #define SHELL_BSIZE 1024
3 #define BSIZE 128
4 #define CONFIG_FILE "/.myshellrc"
5
6 #include <stdio.h>
7 #include <stdlib.h>
8 #include <string.h>
9 #include <dirent.h>
10 #include <unistd.h>
11 #include <errno.h>
12 #include <sys/types.h>
13 #include <sys/wait.h>
14
15 char *WARNINGS = "0";
16
17 int main()
18 {
19 int i;
20 char buffer[BSIZE], *arg = NULL;
21 FILE *f;
22 char *config_path, *str, *config_file = CONFIG_FILE;
23 char *header = "HOME";
24
25 config_path = getenv("HOME");
26
27 str = malloc((strlen(config_path)+strlen(config_file))*sizeof(char));
28 strcpy(str, config_path);
29 strcat(str, config_file);
30
31 printf("config: %s|header: %s\n", str, header);
32
33 for (i = 0; i < BSIZE; i++)
34 buffer[i] = '\0';
35
36 if ((f = fopen(str, "r")) != NULL){
37
38 }
39 else {
40 perror("Unable to open configuration file");
41 }
42 return 0;
43 }

最佳答案

通过从 ENV 获取路径打开文件的示例程序

OpenFile()
{
string filename;
FILE *fp;
filename = string(getenv("HOME")) + "/FileName"; //Home - Configpath, Replace File Name
fp = fopen(filename, "r");
if (fp == NULL ) cout<<"filename read failed"<<endl;
/* Write Code to perform task on File */
fclose(fp); //Close handle
}

要测试你可以制作任何随机文件并尝试 fopen 是否适用于同一路径中的其他文件

if(fp=fopen("/nfs/stak/students/m/morriluk/TESTFILE","r"))

如果上面的代码没有解决问题,请告诉我 unix 风格和带名称的绝对文件路径

关于c - 这些字符串是否为 fopen() 正确连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31526006/

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