C 文件*分配不起作用
我最近有点问题。我想实现我自己的fopen函数以进行错误检查 以下是迄今为止的相关代码:C 文件*分配不起作用,c,file-io,C,File Io,我最近有点问题。我想实现我自己的fopen函数以进行错误检查 以下是迄今为止的相关代码: enum _Errorcode_ openFile( const char * c_str_filename, const char * c_str_mode, FILE* the_file ) { the_file = fopen( c_str_filename, c_str_mode ); if( the_file == NULL ) { return FILE
enum _Errorcode_ openFile( const char * c_str_filename, const char * c_str_mode, FILE* the_file )
{
the_file = fopen( c_str_filename, c_str_mode );
if( the_file == NULL )
{
return FILE_IO_ERROR;
}
else
{
return OK;
}
}
我这样调用函数:
FILE * oFile = NULL;
...
ErrorCode = openFile( "myfile.txt", "r", oFile );
如果我事后检查oFile的指针addr,它仍然指向NULL。
关键是,我的函数恢复正常,没有失败。为什么会这样
该文件存在,如果我调用fopen()函数,一切都会正常工作。由于C总是按值传递,例如,传递给函数的参数是原始变量的副本,因此需要传递指向
文件*
的指针:
enum _Errorcode_ openFile( const char * c_str_filename, const char * c_str_mode,
FILE** the_file )
{
*the_file = fopen( c_str_filename, c_str_mode );
if( *the_file == NULL ) { return FILE_IO_ERROR; }
else { return OK; }
}
由于C总是按值传递,例如传递给函数的参数是原始变量的副本,因此需要传递指向
文件*
的指针:
enum _Errorcode_ openFile( const char * c_str_filename, const char * c_str_mode,
FILE** the_file )
{
*the_file = fopen( c_str_filename, c_str_mode );
if( *the_file == NULL ) { return FILE_IO_ERROR; }
else { return OK; }
}
C按值传递参数,因此您可以将其分配给oFile的一个副本,这就是为什么您在
openFile()
之外看不到更改的原因
将指针传递给它,如下所示:
enum _Errorcode_ openFile( const char * c_str_filename, const char * c_str_mode, FILE** the_file )
{
*the_file = fopen( c_str_filename, c_str_mode );
if( *the_file == NULL )
{
return FILE_IO_ERROR;
}
else
{
return OK;
}
}
....
FILE * oFile = NULL;
...
ErrorCode = openFile( "myfile.txt", "r", &oFile );
C按值传递参数,因此您可以将其分配给oFile的一个副本,这就是为什么您在
openFile()
之外看不到更改的原因
将指针传递给它,如下所示:
enum _Errorcode_ openFile( const char * c_str_filename, const char * c_str_mode, FILE** the_file )
{
*the_file = fopen( c_str_filename, c_str_mode );
if( *the_file == NULL )
{
return FILE_IO_ERROR;
}
else
{
return OK;
}
}
....
FILE * oFile = NULL;
...
ErrorCode = openFile( "myfile.txt", "r", &oFile );
非常感谢你们两位的快速回答。问题是,即使在函数中,fopen后面的指针为NULL,但if仍然失败。奇怪。既然你是第一个,我就认为你的答案是正确的。但也要感谢binyamin;)非常感谢你们两位的快速回答。问题是,即使在函数中,fopen后面的指针为NULL,但if仍然失败。奇怪。既然你是第一个,我就认为你的答案是正确的。但也要感谢binyamin;)