Linux学习笔记-Linux下读写文件
生活随笔
收集整理的這篇文章主要介紹了
Linux学习笔记-Linux下读写文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在Linux編程需要讀寫文件時,有兩種方式:
(1)ANSIC:?使用stdio.h里的函數。fopen,?fclose,?fwrite,?fread
(2)Linux?API:Linux提供了另外一套API用于操作文件。open, close, ?write, ?read
ANSI?C優點:被各平臺都支持,因此一份代碼可以適用多種平臺。
?
ANSIC函數:
(1)文件路徑:?使用/
(2)文本文件時,換行符有區別
windows:?\r\n
linux:?\n
注:換行符是一個約定俗成的東西
?
Linux?API文件操作
以下三者選一:
O_RDONLY?只讀方式
O_WRONLY?以只寫方式打開文件
O_RDWR?以可讀寫方式打開文件
額外的標識位:
O_CREAT可與O_WRONLY聯用,若欲打開的文件不存在則自
動建立該文件
O_TRUNC??可與O_WRONLY聯用,在打開文件時清空文件
O_APPEND可與O_WRONLY聯用,表示追加內容
O_NONBLOCK?表示以“非阻塞”方式讀/寫數據時
?
過程如下:
當前文件和路徑如下:
?
使用ANSIC函數
#include <stdio.h> #include <string.h>int main(){FILE *fp = fopen("/root/CDemo/CFile/a.txt", "wb");if(!fp){printf("open failed!\n");return -1;}char buf[] = "hello\nworld\n";fwrite(buf, 1, strlen(buf), fp);fclose(fp);return 0; }運行截圖如下:
?
使用Linux?API
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>int main(){int fd = open("/root/CDemo/CFile/b.txt", O_WRONLY | O_CREAT, 0644);if(fd < 0){printf("open failed!\n");return -1;}char data[12] = "Linux";write(fd, data, 5);close(fd);return 0; }?
讀取文件:
#include <stdio.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h>int main(){int fd = open("/root/CDemo/CFile/a.txt", O_RDONLY);if(fd < 0){printf("open failed!\n");return -1;}char data[128];int n = read(fd, data, 128);if(n > 0){data[n] = 0;printf("read:%s \n", data);}close(fd);return 0; }運行截圖如下:
新人創作打卡挑戰賽發博客就能抽獎!定制產品紅包拿不停!總結
以上是生活随笔為你收集整理的Linux学习笔记-Linux下读写文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Qt文档阅读笔记-两视图共享模型实现冻结
- 下一篇: Qt工作笔记-对Qt工作线程的进一步理解