为什么“fopen"返回空指针? [英] Why does 'fopen' return a NULL pointer?

查看:40
本文介绍了为什么“fopen"返回空指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C 编程语言开发一个简单的文件拆分器/合并程序.问题是,由于某种原因 fopen 返回 NULL,因此,我的程序在 fwrite 语句处崩溃.我该如何解决这个问题?

I'm working on a simple file splitter/merger program in the C programming language. The problem is, for some reason fopen returns NULL, and because of that, my program is crashing at the fwrite statement. How do I fix this?

这里是 C 文件:

int SplitFile(char* filename, char* output, size_t size)
{
    char current_file_name[256];
    int file_count = 0, i = 0;
    FILE *file = fopen( filename, "rb" );
    printf("split %s into chunks of %d named
", filename, size);

    if (!file)
       return E_BAD_SOURCE;
    else
    {
        output = (char *) malloc(size * sizeof(char));
        if (output == NULL)
            return E_NO_MEMORY;
        else
        {
            int bytes_read = 0;
            FILE *outFile;
            do
            {
                bytes_read = fread(output, sizeof(char), size, file );
                sprintf(current_file_name, "%s%04lu
", "part", file_count++);
                outFile = fopen (current_file_name, "wb" );  // THIS RETURNS NULL
                fwrite(output, sizeof(char), bytes_read, outFile); //CRASHES ON THIS LINE
            }
            while ( bytes_read > 0 )
                ;

            //fclose(outFile);
        }
    }
    fclose(file);
    printf("...
");
    return 0;
}

推荐答案

正确的做法是检查 errnofopen 返回 NULL 时.

The proper thing to do is check errno when fopen returns NULL.

我猜你的问题是你试图写入一个不允许 在文件名中的文件系统,但这也可能是一个权限问题.

I'm going to guess that your problem is that you're trying to write to a filesystem that doesn't allow in filenames, but it could be a permissions issue as well.

这篇关于为什么“fopen"返回空指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆