1.使用open函数新建文件test.c,错误与否都给出提示信息;
2.使用write函数向文件中写入“write to the file!”;错误与否都显示提示信息;
3.显示文件的大小;将文件定位至文件头的位置并从文件中读取10个字节的数据显示。出错给出提示信息。
1 #include<stdio.h>
2 #include<sys/types.h>
3 #include<sys/stat.h>
4 #include<unistd.h>
5 #include<fcntl.h>
6 #include<string.h>
7 #define num 30
8 int main()
9 {
10 int n_fd,ret1,ret2,fsize;
11 char s[20]=“write to the file!”;
12 char a[10];
13
14 if((n_fd=open(“test.c”,O_CREAT|O_RDWR,S_IRWXU))-1)
15 {
16 perror(“creat error”);
17 return -1;
18 }
19
20 ret1=write(n_fd,s,sizeof(s));
21
22 if(ret1-1)
23 {
24 perror(“write error”);
25 return -1;
26 }
27
28 fsize=lseek(n_fd,0,SEEK_END);
29 printf(“The size of file:”);
30 printf("%d\n",fsize);
31 lseek(n_fd,0,SEEK_SET);
32 ret2=read(n_fd,a,10);
33 if(ret2==-1)
34 {
35 perror(“read error\n”);
36 }
37 printf("%s\n",a);
38 close(n_fd);
39 return 0;
40 }