[TOC]
fwrite
size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );
- ptr:指向保存數(shù)據(jù)的指針;
- size:每個數(shù)據(jù)類型的大小
- count:數(shù)據(jù)的個數(shù)
- stream:文件指針
- return 函數(shù)返回寫入數(shù)據(jù)的個數(shù)
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;
}
查看輸出的文件俄认,看到數(shù)據(jù)的存儲是小端對齊
1.png
w wb的區(qū)別
wb 打開或新建一個二進制文件寇荧,在POSIX系統(tǒng),包括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+時候結(jié)果為:
write len=8
-------------
abc
12341234
read length=8
使用w打開時恤煞,結(jié)果為:
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元素的個數(shù)。
這里修改寫下代碼:
#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;
}
結(jié)果為:
write len=8
-------------
6261-d63-310a-3332-34-0-
read length=4
總共9個字節(jié)涎嚼,而實際有效讀入了4個short阱州。
2.png