【问题标题】:unable to open file which is in d: drive无法打开 d: 驱动器中的文件
【发布时间】:2013-11-27 07:11:37
【问题描述】:

如何读写不在C盘的bin目录下的文件。
我写了这段代码

fs=fopen("d:/source.txt","w");
if(fs==NULL)
{
      puts("Unable to open file");
}

它正在输出“无法打开文件”。谁能帮帮我。

【问题讨论】:

  • 使用perror 代替打印错误,它应该更具体地告诉您出了什么问题。
  • 我认为你的斜线是反的。如果你用 \\ 替换 / 会发生什么(这样它就被转义了)?
  • “C 盘”表明这是一台 Windows 机器。在 Windows 中,所有路径都使用反斜杠编写。但由于 C 字符串中的反斜杠具有特殊含义,因此您必须编写 \` to get one. So the path string should be d:\\source.txt`。
  • @Lundin 但是 Windows CRT 不允许两个斜杠作为路径分隔符吗?事实上,Windows 似乎 总是 支持正斜杠作为分隔符。例如,尝试做例如dir "c:/some/path"(注意引号字符)在命令窗口中,你会看到它工作正常。
  • 问题可能是您没有对`D:`的写访问权限,这就是它失败的原因。但这只是一个猜测。您确实必须检查实际错误。

标签: c windows file-handling


【解决方案1】:
FILE *fs= fopen("d:/source.txt","w");
if(fs==NULL)
{
  printf("can't open"); 
}
if (fs!=NULL)
{
    fputs ("Opened successfully",fs);
    fclose (fs);
}

确保 source.txt 文件存在且不是只读的。我试过上面的代码没有任何错误。

【讨论】:

    【解决方案2】:

    无法通过fopen()打开文件的可能原因有多种。

    要获取有关错误详细信息的信息,请打印出errno 和/或致电perror() 和/或strerror(),例如:

    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    
    int main(void)
    {
      char filename[] = "d:/source.txt";
      FILE * fs = fopen(filename,"w");
      if (NULL == fs)
      {
        perror("fopen() failed");
        fprintf(stderr, "Error #%d occurred when trying to open file '%s': %s.\n", 
          errno, 
          filename,
          strerror(errno));
      }
    
      ... 
    
      return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 2021-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-16
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多