<分区>
我的 C 代码遇到了一些问题,因此决定向这里的专家请教我哪里做错了。
//
// Routines.c
//
#include <stdio.h>
#include <errno.h>
...
int OpenFile(FILE * fd, char * nm, char * md){
FILE *rc;
printf("nm = %s, md = %s\n", nm, md);
fd = fopen(nm, md);
printf("fd fopen... errno = %d\n", errno);
if ( fd == NULL ) {
*rc = errno;
printf("fopen %s -> rc = %d\n", nm, *rc);
return rc;
}
printf("fd not NULL !!!\nrc = %d e errno = %d\n", *rc, errno);
return 0;
}
...
int Generate (char * v) {
int rc = 0;
FILE *fd;
rc = OpenFile (fd, v, "w");
if ( rc ){
printf ("open file error. RC = %d", rc);
return rc;
}
if (fd == NULL){
printf ("fd NULL !!!\n");
return 1;
}
CloseFile(fd);
printf("Closed fd\n");
printf("Leaving Generate. RC = %d\n",rc);
return rc;
}
...
这个Routines.c是这样写的:
gcc -Wall -g -O0 -pedantic -fPIC -c Routines.c -o Routines.o
============================================= =================
//
// Caller.c
//
#include <stdio.h>
#include <string.h>
#include "Routines.h"
....
int main (int argc, char **argv) {
....
char * v = "msgs.txt";
....
Generate(v);
....
return 0;
}
这个Caller.c是这样写的:
gcc -Wall -g -O0 -fno-stack-protector -fPIC -c Caller.c
gcc -Wall -g -O0 -fno-stack-protector -fPIC -o Caller Caller.o Routines.o
============================================= =================
两个 c 文件都编译为零错误(也没有警告)。
-- 执行--
msgs from OpenFile() (that is, the file has been opened correctly)
nm = msgs.txt, md = w fd fopen ... 错误号 = 0 fd 不为空! rc = 0 e errno = 0
msgs from OpenFile() (What happen here ???)
fd 为空!!!
有人可以告诉我返回给调用者的文件处理程序发生了什么 为 NULL,当它在文件打开时在例程上正确设置时???
为了解决我的问题,我必须这样做:
FILE * OpenFile(char * nm, char * md, int * rc){
fd = OpenFile (v, "w", &rc);
但我想让自己冷静下来,明白我到底做了什么才发生这种事。
提前(非常)感谢。