![](/img/trans.png)
[英]Why doesn't fwrite() write a Binary File using “wb”, in C, on Mac OS X?
[英]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);
我正在嘗試在wb模式下使用fopen編寫一個二進制文件。 運行程序后,會在適當的位置創建一個具有適當名稱的文件,但是我無法打開或讀取它。 當我嘗試打開它時,會彈出一條消息,提示“無法打開...”。此外,文件本身的名稱在Finder中的格式不正確(在Mac上為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,因此是多余的 malloc
-ing一個字符是無效的-只需使用一個局部變量 wb開頭的文件的長度被截斷為0。 用於同時讀/寫模式或加法模式rb +,a。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.