【问题标题】:Are these strings concatenated correctly for fopen()?这些字符串是否为 fopen() 正确连接?
【发布时间】:2015-10-10 03:17:18
【问题描述】:

我想连接两个字符串 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 }

【问题讨论】:

  • 您没有在str 中为空终止符保留空间,是吗?
  • 1 添加到缓冲区以终止0。确保config_path 以“\\”结尾。尝试打印str
  • 就这么简单? Q_Q 我刚刚在这上面浪费了 4 个小时...非常感谢您的帮助

标签: c unix fopen strcpy strcat


【解决方案1】:

通过从 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风格和带有名称的绝对文件路径

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 1970-01-01
    • 2019-07-17
    • 2011-10-05
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多