【发布时间】:2015-10-10 03:17:18
【问题描述】:
我想连接两个字符串 config_path 和 config_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 }
【问题讨论】:
-
您没有在
str中为空终止符保留空间,是吗? -
将
1添加到缓冲区以终止0。确保config_path以“\\”结尾。尝试打印str。 -
就这么简单? Q_Q 我刚刚在这上面浪费了 4 个小时...非常感谢您的帮助
标签: c unix fopen strcpy strcat