linux下的讀寫打開,讀寫文件操作

#include
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main()
{
int fd = open("./test123", O_RDWR | O_APPEND);       //O_RDWR表示可以進行讀寫操作,O_APPEND表示光標從文檔的文段開始
char str[100] = {0};
if (fd == -1)
{
perror("open:");                  //perror函數:在打印括號裏的內容後輸出文件的錯誤的原因
}
printf("%d\n", fd);
strcpy(str, "helloworld\n");
int count = write(fd, str, strlen(str));                   //寫內容到文件裏,內容爲指針str所指的內存,長度爲strlen(str)
if (count == -1)
{
perror("write fail:");
close(fd);                                                        //寫入失敗,關閉文件


}
    lseek(fd, 0, SEEK_SET);                                        //這個函數是爲了將光標移到文檔開頭
char str2[60] = {0};
    int count2 = read(fd, str2, 100);                                    //讀取文檔內容寫入內存
if (count2 == -1)
{
   perror("read fail:");
close(fd);
}
printf("%s\n", str2);
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章