2015-07-20 58 views
1

我想连接两个字符串config_pathconfig_file并将该字符串传递到fopen()。问题是即使我是100%文件存在,fopen()也会返回一个错误。事实上,我在将命令行传递到fopen()之前先打印字符串,如果我将该字符串直接复制到我的源代码中,则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 } 
+6

你没有预留余地'str'空终止符,是吗? –

+0

将'1'加到缓冲区以终止'0'。确保'config_path'以'\\'结尾。尝试打印'str'。 – AlexD

+0

就这么简单? Q_Q我在这上面浪费了4个小时......非常感谢你的帮助 – loukouk

回答

0

示例程序由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风格和绝对的文件路径与名称