简体   繁体   English

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

[英]Opening a .txt file in Xcode using C and fopen( )

I can't seem to get a file to open in C. What am I doing wrong?我似乎无法在 C 中打开文件。我做错了什么? The file is in the same directory as the .c file and I think I got all the syntax.该文件与 .c 文件位于同一目录中,我想我掌握了所有语法。 Here is a screenshot:这是一个屏幕截图: 在此处输入图片说明

The output says that the file pointer is NULL.输出表明文件指针为 NULL。

For that to work, the "test.txt" has to be in the same directory as the compiled binary (which xcode may not be putting in the same directory as main.c - it may be in Products? I'm not so sure with xcode).为此,“test.txt”必须与编译后的二进制文件位于同一目录中(xcode 可能不会与 main.c 放在同一目录中 - 它可能在产品中?我不太确定与 xcode)。 Try giving the fully-qualified pathname to test.txt in the call to fopen.尝试在调用 fopen 时为 test.txt 提供完全限定的路径名​​。

If fopen fails, fp is set to NULL and errno is set according.如果fopen失败,则 fp 设置为 NULL,并根据设置 errno。 To see why, try:要了解原因,请尝试:

#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);
}

To open the file from any directory, pass the file name in argv, check for arguments and use that parameter to main as the file name( pref. after copying to a dedicated variable).要从任何目录打开文件,请在 argv 中传递文件名,检查参数并使用该参数作为文件名(在复制到专用变量后首选)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM