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

标签 c xcode macos fopen

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

我正在尝试在 wb 模式下使用 fopen 编写一个二进制文件。运行我的程序后,在正确的位置创建了一个正确名称的文件,但我无法打开或读取它。当我尝试打开它时,会弹出一条消息,提示“无法打开...”。此外,文件名称本身在 Finder 中的格式不正确(我在 Mac 上)。名字被抬高了一点。文件肯定看起来有问题。我尝试在 w 模式下使用 fopen 制作一个常规文件,效果很好。所以我很确定在使用 wb 模式编写二进制文件时我只是做错了什么。谁能帮忙?谢谢。

最佳答案

主要问题:

  • 您在读取文件之前没有查找到文件的开头,因此您调用 fread 来读取整个文件将会失败

改变:

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

到:

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

补充说明:

  • sizeof(char) 根据定义为 1,因此是多余的
  • 你不应该cast the result of malloc in C
  • 您应该为任何可能失败的调用添加错误检查,尤其是 I/O 调用
  • malloc - 单个字符效率低下 - 只需使用局部变量
  • 一次读取一个文件的一个字符以确定其长度是非常低效的

关于在 Mac 上的 Xcode 中使用 fopen(fileName, "wb") 后无法访问我的二进制文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33736738/

相关文章:

android - 当两台机器的ip不断变化时,它们如何相互检测?

objective-c - XCode C 编译器错误预期成员名称或声明说明符后的 ';' 预期 ')'

c - 右排列文本中的单词

c - 数组和链表之间的内存使用

c - 作业 : warning: no closing ‘]’ for ‘%[’ format [-Wformat=]

xcode - Facebook SDK 4.0.1 Swift 错误 xcode 6.2 iOS 8.2

xcode - 如何在 Xcode 中删除旧的/未使用的数据模型版本

xcode - 错误 : value of tuple type '(NSString, NSString)' has no member '0'

c++ - 从 ProcessSerialNumber 获取应用程序图标

multithreading - 在Mac OS X上与EnterCriticalSection最佳等效?