[TOC]
fwrite
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
- ptr:指向保存数据的指针;
- size:每个数据类型的大小
- count:数据的个数
- stream:文件指针
- return 函数返回写入数据的个数
int write(const char *path) {
FILE *file = fopen(path, "wb");
if (file == NULL) {
return 0;
}
int arr[4] = {0x00000012, 0x00001234, 0x00123456, 0x12345678};
for (int i = 0; i < 4; i++) {
fwrite(&arr[i], sizeof(int), 1, file);
}
fclose(file);
return 1;
}
查看输出的文件,看到数据的存储是小端对齐
w wb的区别
wb 打开或新建一个二进制文件,在POSIX系统,包括Linux都会忽略该字符。windows文本文件打开时写入\n,会自动加上\r变成\r\n。而已二进制方式打开则不会加上\r。
int write(const char *path) {
FILE *file = fopen(path, "wb+");
// FILE *file = fopen(path, "w");
if (file == NULL) {
return 0;
}
char *p = "abc\n1234";
int len = fwrite(p, sizeof(char), strlen(p), file);
printf("write len=%d\n", len);
fclose(file);
return 1;
}
使用wb+时候结果为:
write len=8
-------------
abc
12341234
read length=8
使用w打开时,结果为:
write len=8
-------------
abc
1234123
read length=9
fread
int read(const char *path) {
FILE *file = fopen(path, "rb");
if (file == NULL) {
return 0;
}
int len = 0;
int total = 0;
char buf[5] = {0};
while (!feof(file)) {
len = fread(buf, sizeof(char), 4, file);
printf("%s", buf, len);
total += len;
}
printf("\nread length=%d", total);
fclose(file);
return 1;
}
注意:fread返回成功有效的读取的item元素的个数。
这里修改写下代码:
#include <stdio.h>
#include <mem.h>
char *PATH1 = "D:\\code\\CProject\\FileByte\\1";
int read(const char *);
int write(const char *);
int main() {
write(PATH1);
printf("-------------\n");
read(PATH1);
return 0;
}
int write(const char *path) {
// FILE *file = fopen(path, "wb+");
FILE *file = fopen(path, "w");
if (file == NULL) {
return 0;
}
char *p = "abc\n1234";
int len = fwrite(p, sizeof(char), strlen(p), file);
printf("write len=%d\n", len);
fclose(file);
return 1;
}
int read(const char *path) {
FILE *file = fopen(path, "rb");
if (file == NULL) {
return 0;
}
int len = 0;
int total = 0;
//使用short
short buf[20] = {0};
while (!feof(file)) {
len = fread(buf, sizeof(short), 20, file);
for (int i = 0; i < len + 2; i++) {
printf("%x-", buf[i]);
}
total += len;
}
printf("\nread length=%d", total);
fclose(file);
return 1;
}
结果为:
write len=8
-------------
6261-d63-310a-3332-34-0-
read length=4
总共9个字节,而实际有效读入了4个short。