C语言文件读写方法

2017-07-13  本文已影响97人  第八区

[TOC]

fwrite

size_t fwrite ( const void * ptr, size_t size, size_t count, FILE * stream );

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

查看输出的文件,看到数据的存储是小端对齐


1.png

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。


2.png
上一篇 下一篇

猜你喜欢

热点阅读