C实现读写文件

https://www.cnblogs.com/zhanghongfeng/p/7726199.html

https://www.cnblogs.com/xudong-bupt/p/3478297.html

https://zhidao.baidu.com/question/196852872.html

第一种方法 open

O_RDONLY: 以只读方式打开文件

O_WRONLY:以只写的方式打开文件

O_RDWR:以读写的方式打开文件

O_CREAT:若打开的文件不存在,则创建该文件

O_EXCL:如果打开文件是设置了O_CREAT,但是该文件存在,则导致调用失败

O_TRUNC:如果以只写或只读方式打开一个已存在的文件,将该文件截至0

O_APPEND:追加的方式打开文件

O_NONBLOCK:用于非堵塞接口i/o

O_NODELAY

O_SYNC:当数据被写入外存或者其他设备后,操作才返回。

int writeFile(const unsigned char *write_buff, uint write_bytes,
        char *path) {
    int d;
    if ((d = open(path, O_RDWR | O_APPEND |O_CREAT)) == -1) {
        perror("open file failed\n");
        return -1;
    }
    if (write(d, write_buff, write_bytes) == -1) {
        perror("write data fail\n");
        close(d);
        return -1;
    }
    close(d);
    sync();
    return 0;
View Code
int readFile(unsigned char* read_buff, uint &read_bytes, char *path) {
    int fd;
    if ((fd = open(path, O_RDONLY)) == -1) {
        perror("open file failed\n");
        return 0;
    }
    read_bytes = read(fd, read_buff, 2000);
    close(fd);
    return read_bytes;
View Code

第二种方法 fopen

"r ":只读方式打开一个文本文件 "rb ": 只读方式打开一个二进制文件 
"w ":只写方式打开一个文本文件 "wb ": 只写方式打开一个二进制文件
"a ":追加方式打开一个文本文件 "ab ": 追加方式打开一个二进制文件
"r+ ":可读可写方式打开一个文本文件 "rb+ ": 可读可写方式打开一个二进制文件
"w+ ":可读可写方式创建一个文本文件 "wb+ ": 可读可写方式生成一个二进制文件
"a+ ":可读可写追加方式打开一个文本文件 "ab+ ": 可读可写方式追加一个二进制文件
返回值: 文件指针,如返回为NULL,表示打开失败

注意

  (1)写操作fwrite()后必须关闭流fclose()。

  (2)不关闭流的情况下,每次读或写数据后,文件指针都会指向下一个待写或者读数据位置的指针。

int writeFile(const unsigned char *write_buff, uint write_bytes,
        char *path) {
    FILE *file;
    if ((file = fopen(path, "aw+")) == NULL) {
        perror("fopen() error.Open file failed\n");
        return -1;
    }
    int res = fwrite(write_buff, sizeof(unsigned char), write_bytes, file);
    fflush(file);
    fclose(file);
    return res;
}
View Code
int readFile(unsigned char* read_buff, uint &read_bytes, char *path) {
    FILE* file;
    if ((file = fopen(path, "r")) == NULL) {
        perror("fopen() error.Open file failed\n");
        return -1;
    }
    read_bytes=fread(read_buff,sizeof(unsigned char),MAX_BUFF,file);
    fclose(file);
    return read_bytes;
}
View Code

 

 

 

要点:追加方式写文件,fwrite四个参数的意义,fflush

以及遇到的问题O_APPEND到底有没有作用

应该是一直有效的,以前好像是和O_TRUNC连用了的原因。

以及O_CREAT出现的问题 open with O_CREAT in second argument needs 3 arguments

现在不知道为什么不能重现这个问题了。

write注意点

如果文件原来有“你好”二字,以非追加写入“你”,文件依然是你好,所以有些情况要注意使用O_TRUNC。

posted @ 2017-12-04 15:09  _离水的鱼  阅读(397)  评论(0编辑  收藏  举报