Linux下C語言的檔案操作
檔案的讀寫
代碼
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#define BUFFSIZE 512
#define MSG "hhhh9999"
int main(int main, char * argv[])
{
int fd = -1;
int rv = -1;
char buf[BUFFSIZE] = MSG;
fd = open("text.txt", O_RDWR | O_CREAT | O_TRUNC, 0666);
if(fd<0)
{
perror("opne file error");
return 0;
}
printf("open file return :%d\n",fd);
rv = write(fd, buf, strlen(MSG));
if(rv<0)
{
perror("write file error");
printf("write file error: %s\n",strerror(errno));
goto cleanup;
}
printf("write file %d bytes\n",rv);
//memset(buf, 0, sizeof(buf)); //記憶體清零
lseek(fd, 0, SEEK_SET);
rv = read(fd, buf,sizeof(buf));
if(rv<0)
{
perror("read file error");
printf("read file error: %s\n",strerror(errno));
goto cleanup;
}
printf("read file %d bytes :%s\n", rv, buf);
cleanup:
close(fd);
return 0;
}
運行結果:
tianyujie@icloud-1st:~$ gcc cp.c
tianyujie@icloud-1st:~$ ./a.out
open file return :3
write file 8 bytes
read file 8 bytes :hhhh9999
tianyujie@icloud-1st:~$
我的錯誤:
忘記在write時把MSG傳給buf,導致text.txt里全是亂碼,
prerror()與strerror(errno) 作用一樣,都是回傳錯誤,但是strerror(errno)能回傳具體錯誤原因,好用一點,
open()函式可以創建或打開一個檔案,
int fd = -1;
fd = open("test.txt", O_RDWR | O_TRUNC | O_CREAT,0666);
第一個引數:檔案的絕對路徑
第二個引數:函式的具體作用
| oflag | 作用 |
|---|---|
| O_WRONLY | 只寫 |
| O_RDWR | 讀寫 |
| O_RDONLY | 只寫 |
O_CREAT 如果檔案不存在,則創建該檔案
O_TRUNC 如果此檔案存在,而且為 只寫 或 讀-寫 成功打開,則將其長度截斷為0
第三個引數:給檔案權限(也可省略)
open的回傳值為最小未用檔案描述符
write()系統呼叫,
第一個引數是文集描述符fd,第二個引數是要寫的內容,第三個引數是要寫的位元組數;
此函式是將 buf 里的內容傳給 fd ,
read()系統呼叫,
第一個引數是文集描述符fd,第二個引數是要讀的內容,第三個引數是要讀的位元組數;
此函式是將 fd 的內容傳給 buf ,
如果read成功,回傳獨到的位元組數,如果讀到檔案的尾端,回傳 0,
若在到達檔案尾端之前有30位元組,而要求讀100位元組,則read回傳 30 ,下次呼叫read時,回傳 0 ,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/252234.html
標籤:其他
下一篇:解決kali中無法正常復制
