简体   繁体   English

在Mac上的Xcode中使用fopen(fileName,“ wb”)之后无法访问我的二进制文件

[英]Can't access my binary file after using fopen(fileName, “wb”) in Xcode on Mac

FILE* inFile = fopen(inF, "rb");
if (inFile == NULL) {
    printf("Invalid input!\n");
    exit(EXIT_FAILURE);
}

char* bigBuffer;
char* nextChar = (char*) malloc(sizeof(char));
unsigned long i = 0;
unsigned long j;
while ((j = fread(nextChar, sizeof(char), 1, inFile)) == 1) {
    i += j;
}
bigBuffer = malloc(i * sizeof(char));
fread(bigBuffer, sizeof(char), i, inFile);
fclose(inFile);
printf("%s\n", outF);
FILE* outFile = fopen(outF, "wb");
//if (outFile == NULL)
    //printf("null\n");
j = fwrite(bigBuffer, sizeof(char), i, outFile);
printf("%lu\n", j);
fclose(outFile);
free (bigBuffer);
free (nextChar);

I'm trying to write a binary file using fopen in wb mode. 我正在尝试在wb模式下使用fopen编写一个二进制文件。 After running my program, a file of the proper name is made in the proper place, but I just can't open it or read it. 运行程序后,会在适当的位置创建一个具有适当名称的文件,但是我无法打开或读取它。 When I try to open it, a message pops up saying "Can't open...." In addition, the name of the file itself isn't formatted properly in Finder (I'm on a Mac). 当我尝试打开它时,会弹出一条消息,提示“无法打开...”。此外,文件本身的名称在Finder中的格式不正确(在Mac上为Mac)。 The name is elevated and cut off a little. 名字被抬高了并且被切断了一点。 It definitely looks like something is wrong with the file. 看起来文件肯定有问题。 I tried just making a regular file using fopen in w mode, and that worked beautifully. 我尝试仅在w模式下使用fopen制作常规文件,并且效果很好。 So I'm pretty sure I'm just doing something wrong when it comes to writing binary files using wb mode. 因此,我很确定在使用wb模式写入二进制文件时,我只是做错了什么。 Can anyone help? 有人可以帮忙吗? Thanks. 谢谢。

The main problem: 主要问题:

  • you didn't seek to the beginning of the file before reading, so your call to fread to read the entire file will fail 您在读取之前没有搜索文件的开头,因此调用fread读取整个文件将失败

Change: 更改:

bigBuffer = malloc(i * sizeof(char));
fread(bigBuffer, sizeof(char), i, inFile);

to: 至:

bigBuffer = malloc(i);              // allocate buffer
rewind(inFile);                     // reset file pointer to start of file
fread(bigBuffer, 1, i, inFile);     // read entire file

Additional notes: 补充笔记:

  • sizeof(char) is 1 by definition, and therefore redundant sizeof(char)根据定义为1,因此是多余的
  • you should not cast the result of malloc in C 你不应该在C中强制转换malloc的结果
  • you should add error checking to any call that might fail, especially I/O calls 您应该将错误检查添加到任何可能失败的调用中,尤其是I / O调用
  • malloc -ing a single char is inefficient - just use a local variable malloc -ing一个字符是无效的-只需使用一个局部变量
  • reading a file one char at a time to determine its length is very inefficient 一次读取一个字符以确定其长度的文件效率很低

The file with the opening in wb truncated to 0 length. wb开头的文件的长度被截断为0。 Use for simultaneous read / write mode or addition mode rb +, a. 用于同时读/写模式或加法模式rb +,a。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM