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)复制到另一个文件中