Linux--创建、打开、写入文件操作

  • 格式:docx
  • 大小:20.62 KB
  • 文档页数:3

Linux下创建、打开、写入文件操作
linux下既然把所有的设备都看作文件来处理,就要熟练使用linux下文件操作的相关API。

1.#include<stdio.h>
2.
3.#include<sys/types.h>
4.#include<sys/stat.h>
5.#include<fcntl.h>
6.
7.#define LENGTH 100
8.
9.int main(int argc,char* argv[])
10.{
11.int fd,len;
12.char str[LENGTH];
13.char *content="hi!";
14.char *path="/tmp/test.txt";
15.if(argc<2){
16. printf("Usage:Please pass the content as argument!\n");
17. exit(1);
18. }
19. content=argv[1];
20. fd=open(path,O_CREAT|O_RDWR,S_IRUSR|S_IWUSR);
21.if(fd<0){
22. printf("Fail to open or create file!\n");
23. exit(1);
24. }
25.if(write(fd,content,strlen(content))!=strlen(content)){
26. printf("write error!\n");
27. exit(1);
28. }
29. close(fd);
30.
31.if((fd=open(path,O_RDWR))<0){
32. printf("Fail to open file!\n");
33. exit(1);
34. }
35.if((len=read(fd,str,LENGTH))<0){
36. printf("Read file error!\n");
37. exit(1);
38. }
39. str[len]='\0';
40. printf("%s\n",str);
41. close(fd);
42.return 0;
43.}
用malloc函数代替数组str,根据要打印的内容长度动态申请内存:
1.#include<stdio.h>
2.
3.#include<sys/types.h>
4.#include<sys/stat.h>
5.#include<fcntl.h>
6.
7.//#define LENGTH 100
8.
9.int main(int argc,char* argv[])
10.{
11.int fd,len;
12.// char str[LENGTH];
13.char *str;
14.char *content="hi!";
15.char *path="/tmp/test.txt";
16.if(argc<2){
17. printf("%s\n",content);
18. printf("Usage:Please pass the content as argument!\n");
19. exit(1);
20. }
21. content=argv[1];
22. fd=open(path,O_CREAT|O_RDWR,S_IRUSR|S_IWUSR);
23.if(fd<0){
24. printf("Fail to open or create file!\n");
25. exit(1);
26. }
27.if(write(fd,content,strlen(content))!=strlen(content)){
28. printf("write error!\n");
29. exit(1);
30. }
31. close(fd);
32.
33.if((fd=open(path,O_RDWR))<0){
34. printf("Fail to open file!\n");
35. exit(1);
36. }
37. str=malloc(strlen(content));
38.if((len=read(fd,str,strlen(content)))<0){
39. printf("Read file error!\n");
40. exit(1);
41. }
42.// str[len]='\0';
43. printf("%s\n",str);
44. free(str);
45. close(fd);
46.return 0;
47.}。