c - OpenFile 函数打开文件正常但返回 NULL 指针(C 程序)

标签 c linux

<分区>

我的 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);

但我想让自己冷静下来,明白我到底做了什么才发生这种事。

提前(非常)感谢。

最佳答案

OpenFile() 中的

FILE * fd 是包含文件指针的局部变量。您正在更改本地函数范围内的指针 - 这些信息都不会从您的 OpenFile() 函数中获取。

关于c - OpenFile 函数打开文件正常但返回 NULL 指针(C 程序),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47636659/

相关文章:

c - C 编程的嵌套循环

c - 插入排序调试帮助

c - sigset_t 在这种情况下有用吗?

python - 从一个非常大的文件中选择一个随机行,从命令行

Linux僵尸进程Xsession

C# 培训测验

c - 优化 realloc 函数

linux - 为什么 bash/echo 在此 CMake 脚本中不起作用?

linux - Bash Ping 站点检查脚本。 (超时时间更长)

java - 为USB端口设置套接字作为TCP双向通信