【发布时间】:2016-09-20 23:40:42
【问题描述】:
我正在尝试用 c 测试写入二进制文件,只是想了解我的输出。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void writeToFile();
int main(void) {
writeToFile();
return(0);
}
void writeToFile() {
FILE * file = fopen("file.bin","w");
char * string;
if(file == NULL)
printf("Problem with file\n");
string = malloc(sizeof(char)*6);
strcpy(string,"Hello");
fwrite(&string,sizeof(string),strlen(string)+1,file);
fclose(file);
}
我正在使用命令解释我的结果:
od -c file.bin
显示八进制输出。 并给我这个:
0000000 @ 022 # 001 \0 \0 \0 \0 020 020 # 001 \0 \0 \0 \0
0000020 300 016 374 ? 377 177 \0 \0 264 006 @ \0 \0 \0 \0 \0
0000040 @ \a @ \0 \0 \0 \0 \0 200 365 c 274 020 177 \0 \0
0000060
我不知道如何解释这个输出,我知道它是八进制的,但我怎么知道我的字符串“Hello”写得正确?
我在想我可以使用 ascii 表将输出转换为 ascii,但我不确定这是否可行?有没有一种简单的方法可以检查字符串“Hello”是否正确写入?
也许我可以读回输出,并以某种方式检查其中是否存在字符串“Hello”?
任何帮助将不胜感激。
【问题讨论】:
-
您正在将“字符串”的地址传递给 fwrite。你应该传递它的值。
-
以十六进制显示输出可能更容易(我使用
od -Ax -t x1 -
你正在写 指针
string(不是它指向的东西,它是字符串),以及一堆恰好在它后面的垃圾。 -
如果您希望完全控制读取和写入的内容,您应该使用模式
wb而不是w打开文件。仅将fopen()与w一起使用不适合二进制模式。
标签: c file binaryfiles