【问题标题】:Opening a .txt file in Xcode using C and fopen( )使用 C 和 fopen() 在 Xcode 中打开一个 .txt 文件
【发布时间】:2020-03-06 11:35:34
【问题描述】:

我似乎无法在 C 中打开文件。我做错了什么?该文件与 .c 文件位于同一目录中,我想我掌握了所有语法。这是截图:

输出表明文件指针为 NULL。

【问题讨论】:

标签: c file text-files


【解决方案1】:

为此,“test.txt”必须与已编译的二进制文件位于同一目录中(xcode 可能不会与 main.c 放在同一目录中 - 它可能在 Products 中?我是对xcode不太确定)。尝试在对 fopen 的调用中为 test.txt 提供完全限定的路径名​​。

【讨论】:

    【解决方案2】:

    如果fopenfails,fp 设置为 NULL,errno 设置相应。要了解原因,请尝试:

    #include <stdio.h>
    #include <string.h>
    #include <errno.h>
    
    int
    main( void )
    {
      int status = EXIT_SUCCESS;
      FILE *fp = fopen(“test.txt”, “r”);
      if( fp == NULL )
      {
        fprintf( stderr, “Errno %d, Error %s, opening text.txt for reading.\n”, errno, strerror(errno));
        status = errno;
      }
    
      // Do something with fp...
      return(status);
    }
    

    要从任何目录打开文件,请在 argv 中传递文件名,检查参数并将该参数作为文件名使用 main (首选在复制到专用变量后)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-08-12
      • 1970-01-01
      • 2021-07-15
      • 1970-01-01
      • 2015-07-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多