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

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

问题描述

我工作在C编程语言中一个简单的文件分路器/合并程序。问题是,由于某些原因的fopen 的返回NULL,并且因为这一点,我的计划是在 FWRITE 声明崩溃。我该如何解决这个问题?

下面是C文件:

  INT SplitFile(字符*文件名字符*输出,为size_t大小)
{
    焦炭current_file_name [256];
    INT FILE_COUNT = 0,I = 0;
    FILE *文件=的fopen(文件名,RB);
    的printf(分裂%s转换%d个命名的\\ n块,文件名,大小);    如果(!文件)
       返回E_BAD_SOURCE;
    其他
    {
        输出=(字符*)malloc的(大小*的sizeof(字符));
        如果(输出== NULL)
            返回E_NO_MEMORY;
        其他
        {
            INT bytes_read缓存= 0;
            FILE *不过outFile;
            做
            {
                bytes_read缓存= FREAD(输出的sizeof(炭),大小,文件);
                sprintf的(current_file_name,%s%04lu \\ n,部分,FILE_COUNT ++);
                不过outFile = FOPEN(current_file_name,WB); //返回null
                FWRITE(输出的sizeof(炭),bytes_read缓存,不过outFile); //坠毁在这一行
            }
            而(bytes_read缓存大于0)
                ;            // FCLOSE(不过outFile);
        }
    }
    FCLOSE(文件);
    的printf(... \\ n);
    返回0;
}


解决方案

做的正确的事是检查<一个href=\"https://stackoverflow.com/questions/503878/how-to-know-what-the-errno-means\"><$c$c>errno的fopen 收益 NULL

我要去猜测,你的问题是,你尝试写入文件系统不允许 \\ n 中的文件名,但它可能是权限问题为好。

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?

Here is the C file:

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\n", 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\n", "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("...\n");
    return 0;
}

解决方案

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 \n in filenames, but it could be a permissions issue as well.

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

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