您好,登錄后才能下訂單哦!
Linux系統打開文件的正確方法是什么,針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
文件的打開open函數 涉及頭文件: ubuntu 頭文件所在目錄:/usr/include/x86_64-linux-gnu/sys #include
參數解釋:
功能:給文件出昂見一個新的文件描述符,
pathname:指定一個文件路徑
flags: 讀取文件的模式O_RDONLY, O_WRONLY, or O_RDWR
mode:讀取文件的權限指定
S_IRWXU == 00700 用戶有 讀寫執行權限 S_IRUSR 00400 user has read permission S_IWUSR 00200 user has write permission S_IXUSR 00100 user has execute permission S_IRWXG 00070
group has read, write and execute permission S_IRGRP 00040
group has read permission S_IWGRP 00020
group has write permission S_IXGRP 00010
group has execute permission S_IRWXO 00007 others have read, write and execute permission S_IROTH 00004 others have read permission S_IWOTH 00002 others have write permission S_IXOTH 00001 others have execute permission
返回值: successfully 返回一個文件描述符非負整數,
#include #include #include #include int main(int argc, char*argv[]) { int fd = 0; fd=open("./open_1.c",O_RDONLY); printf("fd = %d \r\n", fd); return 0 ; } 1234567891011121314 輸出結果: fd = 3 12
這里只有讀取的權限,嘗試這讀取下這個文件的內容并輸出至屏幕; 這里就要用到 read 函數: man 2 read 查看具體解釋 #include
讀取結果: buffer= #include #include #include #include #include int display_file(int,int); int main(int argc, char*argv[]) { int fd = 0; fd=open("./open_1.c",O_RDONLY); //printf("fd = %d \r\n", fd); display_file(fd, 1024); return 0 ; } int display_file(int fd, int count) { char buffer[100]; memset(buffer, 0, sizeof(buffer)); if(0 > fd || 0 >= count) return -1; int read_num = read(fd,buffer,count); if (read_num return -1; else return read_num; fprintf(stdout,"buffer= %s read_num = %d ",buffer, read_num); } read_num = 520 好巧不巧剛好讀取了520個字節哈哈 123456789101112131415161718192021222324252627282930313233
這里需要注意的是: buffer申請的空間大小必須大于等于 count ,不然會報總線錯誤;
man 2 write #include
#include #include #include #include #include int display_file(int,char *, int); int main(int argc, char*argv[]) { int fd = 0; int fdw = 0; char buffer[1024]; memset(buffer, 0, sizeof(buffer)); fd=open("./open",O_RDONLY); fdw = open("./open_2", O_RDWR|O_CREAT, S_IWUSR|S_IRUSR|S_IROTH); //printf("fd = %d \r\n", fd); display_file(fd, buffer,1024); write_to_file(fdw,buffer,1024); return 0 ; } int display_file(int fd, char * buf, int count) { char * buffer = NULL; buffer = buf; if(0 > fd || 0 >= count || NULL == buf) return -1; int read_num = read(fd,buffer,count); if (read_num return -1; else return read_num; fprintf(stdout,"buffer= %s read_num = %d \r\n",buffer, read_num); } int write_to_file(int fd,char* buff, int count) { int write_num = write(fd, buff,count); if (write_num return -1; else return write_num; }
關于Linux系統打開文件的正確方法是什么問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。