【问题标题】:NULL memories entryNULL 记忆条目
【发布时间】:2016-12-13 09:15:00
【问题描述】:

我编写了这个小程序,它以二进制形式读取文件(本例中为 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;
}

【问题讨论】:

  • fopen_s 函数调用的返回值是多少?如果sourceNULL,你一定不能close() 它。
  • 查看msdn示例中fopen_s的返回值msdn.microsoft.com/en-us/library/z5hh6ee9.aspx
  • 文件是否与可执行文件位于同一文件夹中?
  • 注意:你mallocated 的内存不是freed。
  • 为什么不能使用fopen,而当它失败时,使用perror?喜欢here

标签: c


【解决方案1】:

这对我有用。您应该将 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);
    }

【讨论】:

  • 可能应该是==,就像他对target所做的那样。但是fclose 不应该在那里。
  • 是的,我终于看到了:)
  • 我的“cpydatabases.db”大小不同(数据库 7KB,cpydatabases 2KB)...代码有效,但我无法弄清楚 &source 内存地址中出了什么问题,为什么它为空
  • 两个数组:source_file[]target_file[] 未使用。声明:fclose( target ); 应该说:fclose( source );
  • 是的,它们是我对代码进行的最后一次更新的剩余部分......抱歉发布它们
【解决方案2】:

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

【讨论】:

  • 我已将文件与 .exe 放在同一目录中,但问题仍然相同
猜你喜欢
  • 2013-11-05
  • 1970-01-01
  • 2020-02-04
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
  • 2013-05-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多