1. 程式人生 > >Linux 檔案系統呼叫(習題)

Linux 檔案系統呼叫(習題)

1 設計一個程式,要求開啟檔案"pass",如何沒有這個檔案,新建此檔案,許可權設定為只有所有者有隻讀許可權。

程式程式碼:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
int main()
{
int fd;

fd=open("pass",O_CREAT|O_RDWR,0400);  //0400 =  -r--------  許可權設定
close(fd);
}

2 設計一個程式,要求新建一個檔案"hello",利用write函式將"Linux下C軟體設計"字串寫入該檔案

程式程式碼:

#include <fcntl.h>
#include <string.h>
#include <stdio.h>
#define LENGTH   100
int main()
{
int fd;
char *buf="Linux下C軟體設計";
fd=open("hello.txt",O_CREAT|O_RDWR,0777);
write(fd,buf,LENGTH);
close(fd);
}

3 設計一個程式,要求利用read函式讀取系統檔案"/etc/passwd",並在中端顯示輸出

程式程式碼:

#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>


#define   SIZE  1024*16    //定義讀取最大程度為16K
int main()
{
int fd,n;
char buf[SIZE];
fd=open("/etc/passwd",O_RDONLY);
        n=read(fd,buf,SIZE);
printf("%s",buf);

close(fd);

}

4 設計一個程式,要求複製檔案/etc/passwd 到指定的檔案中
  例如 copy /home/ab.bak  將/etc/passwd複製到/home/ab.bak中

程式程式碼:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>


#define SIZE  (1024*2)
int main()
{
        int fd1, fd2,len;
char str[SIZE];
fd1=open("/etc/passwd",O_RDWR);
fd2=open("/home/ab.bak",O_CREAT|O_RDWR,0777);
len=read(fd1,str,SIZE);
str[len]='\0';
write(fd2,str,len);   //為避免出現亂碼,這裡所寫入的字串長度為讀到的長度。
close(fd1);
close(fd2);

}



5 用多執行緒(4個執行緒)將一個大檔案(32M)複製到另一個檔案中