示例1:向test.txt檔案中寫入資料
test.txt(假設已存在的test.txt的檔案內容為123456789)
file1.c
#include #include #include #include #include #include #include #include int main()
//設定檔案許可權掩碼
umask(0);
//建立檔案
fd = open(filename,o_rdwr | o_creat,0777);
//如果開啟檔案失敗
if(fd < 0)
//設定檔案偏移,從檔案尾開始
lseek(fd,0,seek_end);
//緩衝區內資料為abcdefg
char buffer[1024]="abcdefg";
//寫資料,將緩衝區內的資料全部一次性寫入
int w_len = write(fd,buffer,strlen(buffer));
printf("write len=%d\n",w_len);
//設定檔案的偏移量為0,即檔案的開始位置
lseek(fd,0,seek_set);
//讀資料
char readbuffer[1024]=;
int nsize = read(fd,readbuffer,1024);
printf("%s\n",readbuffer);
struct stat st;
if(fstat(fd,&st) < 0)
printf("%s『s size=%d\n",filename,st.st_size);
//改變檔案大小
ftruncate(fd,7);
//關閉檔案
close(fd);
return 0;
}
編譯並執行:gcc file1.c -o file1
![](https://pic.w3help.cc/2b0/539e8c343d0cc978c5c08be94183d.jpeg)
之後再檢視test.txt檔案,發現內容已經改變。
示例2:複製檔案(把b.txt檔案內容複製到a.txt中)
b.txt
copyfile2.c
#include #include #include #include #include #include int main()
; //s_irusr=0400,許可權為使用者唯讀
fdin = open("b.txt",o_rdonly,s_irusr);
if(-1 == fdin)
//建立檔案a.txt,許可權為使用者可讀可寫可執行
fdout = creat(pathname,s_irwxu);
if(-1 == fdout)
//讀檔案b.txt
size=read(fdin,buffer,1024);
if(size > 0)
close(fdout);
close(fdin);
return 0;
}
編譯並執行:gcc copyfile2.c -o copyfile2
![](https://pic.w3help.cc/56b/5d1d87f88e38d93204086a38370f0.jpeg)
示例3:測試檔案型別(目錄檔案、普通檔案、裝置檔案等)
file3.c
#include#include#include#include#include#includeint main()
//開啟目錄
p_dir=opendir(filename);
if(null==p_dir)
struct dirent *p_dirent=null;
while((p_dirent=readdir(p_dir))!=null)
if(p_dirent->d_type==dt_dir)
else if(p_dirent->d_type==dt_reg)
else
}closedir(p_dir);
return 0;
}
編譯並測試執行:gcc file3.c -o file3
![](https://pic.w3help.cc/197/3cec52782c81735538dc7767834f3.jpeg)
示例4:列印目錄
列印當前目錄下的各個檔名
file4.c
#include#include#include#include#include#include#includevoid printdir(char* dir,int depth)
//切換到dir目錄
chdir(dir);
while((entry=readdir(dp))!=null)
printf("%*s%s\n",depth,"",entry->d_name);
//遞迴呼叫
printdir(entry->d_name,depth+4);
}else
}chdir("..");
closedir(dp);
}int main()
編譯並執行:gcc file4.c -o file4
![](https://pic.w3help.cc/35b/c84f07187130a523091555828d5b1.jpeg)
python之作業系統相關練習
題目要求 在當前目錄新建目錄img,裡面包含多個檔案,檔名各不相同 x4g5.png 將當前img目錄所有以.png結尾的字尾名改為.jpg import random import string import os def gen code len 4 隨機生成四位隨機數 li random.sa...
Linux學習之檔案操作相關
touch命令 建立檔案,檔名如果不存在則建立,如果存在則更改訪問時間 touch opertion dirname1 dirname2 rm命令 刪除檔案或者檔案目錄 r 遞迴刪除子目錄 rm rf 刪除當前目錄的全部內容 強制刪除目錄所有東西 cp拷貝檔案或者目錄 cp option scrpa...
檔案操作相關
檔案拷貝ssize t sendfile int out fd,int in fd,off t offset,size t count sendfile 是作用於資料拷貝在兩個檔案描述符之間的操作函式.這個拷貝操作是核心中操作的,所以稱為 零拷貝 sendfile函式比起read和write函式高效...