简体   繁体   中英

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? The file is in the same directory as the .c file and I think I got all the syntax. Here is a screenshot: 在此处输入图片说明

The output says that the file pointer is 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). Try giving the fully-qualified pathname to test.txt in the call to fopen.

If fopen fails, fp is set to NULL and errno is set according. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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