使用C和fopen()在Xcode中打开.txt文件

问题描述 投票:0回答:2

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

输出表明文件指针为NULL。

c file text-files
2个回答
1
投票

要使其正常工作,“ test.txt”必须与已编译的二进制文件位于同一目录中(xcode可能与main.c不在同一目录中-可能在Products中?因此请确保使用xcode)。尝试在对fopen的调用中将完全限定的路径名​​赋予test.txt。


0
投票

如果fopen失败,则将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中传递文件名,检查参数,并使用该参数作为文件名(复制到专用变量后优先)。

© www.soinside.com 2019 - 2024. All rights reserved.