空记忆条目

时间:2016-12-13 09:15:01

标签: c

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

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

该程序在2015年Visual Studio中运行。

#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;
}

2 个答案:

答案 0 :(得分:1)

这对我有用。您应该将Databases.db文件放在与source.cpp文件相同的文件夹中,或使用类似&#34; C:/ Databases&#34;的绝对路径。无论如何,这段代码对我有用:

#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);
    }

答案 1 :(得分:0)

我认为“Databases.db”与可执行文件不在同一目录中。 您可以提供“Databases.db”的完整路径,也可以将此文件复制到.sln文件所在的位置。