c - 空内存条目

标签 c

我编写了这个小程序,它读取二进制形式的文件(本例中为 Databases.db)并将其内容复制到 cpydatabases.db 中...

当我在 fopen_s(&source, "Databases.db", "r"); 中运行调试器时,source总是NULL (调试时显示内存条目始终为 Null, 0x000000000000 <NULL> )。

该程序在 Visual Studio 2015 中运行。

#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include "dirent.h"
#include <string.h>
#include <sys/stat.h>
#include <stdlib.h>

#define BUFFSIZE 2048
char ch, *readbuf;
int nread, nwrit;
FILE *source, *target;

int main()
{
    int returnv;
    fopen_s(&source, "Databases.db", "r");

    if ( source !== NULL)
    {
        fclose(source);
        return (EXIT_FAILURE);
    }
    fopen_s(&target,"cpydatabases.db", "w");
    //check again
    if (target == NULL)
    {
        fclose(target);
        return(EXIT_FAILURE);
    }
    //setting the char that reads the binary
    readbuf = (char *)malloc(BUFFSIZE* sizeof(char));

    if (readbuf == NULL)
    {
        fclose(source);
        fclose(target);
        return(EXIT_FAILURE);
    }

    while (1)
    {
        nread = fread((void *)readbuf, sizeof(char), BUFFSIZE, source) ;
        // fwrite((void *)readbuf, sizeof(char), nread, target);
        nwrit = fwrite((void *)readbuf, sizeof(char), nread, target);
        if (nwrit < nread)
        {
            returnv = (EXIT_FAILURE);
        }
        if (nread <= BUFFSIZE)
        { 
            returnv = (EXIT_SUCCESS);
            break;
        }    
    }

    fclose(source);
    fclose(target);

    return 0;
}

最佳答案

这对我有用。您应该将 Databases.db 文件与 source.cpp 文件放在同一文件夹中,或者使用绝对路径,例如“C:/Databases”。无论如何,这段代码对我有用:

#define BUFFSIZE 2048
char ch, source_file[50], target_file[50], *readbuf;
int nread, nwrit;

FILE *source, *target;
int main()
{

    int returnv;
    fopen_s(&source, "Databases.db", "r");

    if (source == NULL)
    {
        //fclose(source);
        return (EXIT_FAILURE);
    }
    fopen_s(&target, "cpydatabases.db", "w");
    //check again
    if (target == NULL)
    {
        fclose(target);
        return(EXIT_FAILURE);
    }

关于c - 空内存条目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41117290/

相关文章:

c++ - 创建 gnome-shell 小程序/小部件?

c - 在 C 中使用动态二维数组绘制网格

ios - Xcode 6.3 上架构 x86_64 的 undefined symbol

c - 在 C 中调用 fgets 时出现段错误

c - 在 C 中寻找质因数

c++ - 帮助我开始(流量操纵)

c++ - (void)变量的意义

c - ARM 处理器是否可行?

c - 配置文件 C 执行

c - 查找矩阵中的最大元素