要使其正常工作,“ test.txt”必须与已编译的二进制文件位于同一目录中(xcode可能与main.c不在同一目录中-可能在Products中?因此请确保使用xcode)。尝试在对fopen的调用中将完全限定的路径名赋予test.txt。
如果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中传递文件名,检查参数,并使用该参数作为文件名(复制到专用变量后优先)。