[转]Linux文件操作函数open close read write等示例

//fileopen.c

#include<stdio.h>

#include<string.h>

#include<sys/types.h>

#include<sys/stat.h>

#include<fcntl.h>

#include<unistd.h>



int main()

{

‍ char temp[]="hello,abc!";

int fd;

char pathname[255];

if((fd=open("fileopen.txt",O_WRONLY|O_CREAT,0640))==-1)

{

printf("creat file wrong!");

}

int len=strlen(temp)+1;

write(fd,temp,len);//若fd为0,或这里直接写0,则会输出到屏幕上而不写入文件中

close(fd);

}


//fileopen2.c


#include<sys/types.h> 

#include<sys/stat.h> 

#include<unistd.h> 

#include<fcntl.h> 

#include <stdio.h>

int main() 

{

int fa; 

int s=12;

int len;

char text[20]="hello,fileopen2!!!";

fa=open("fileopen2.txt",O_WRONLY|O_CREAT,0640);

//len = sprintf(text, "%d", s);

write(fa,text,sizeof(text)); 

close(fa); 

}


//test_system_fprintf_fopen.c


#include<stdio.h>

#include<stdlib.h>

int main()

{

FILE *stream;

char temp[255];

char *a="hello,c!";

stream=fopen("fprintf.txt","w");

fprintf(stream,"%s\n",a);

fprintf(stream,"sb,c++\n");

sprintf(temp,"nl fprintf.txt");

fclose(stream);

printf("%s\n",temp);

system(temp);//system函数参数可以为字符串指针或直接字符串

system("nl fprintf.txt");

exit(0);

return 0;

}



//file-rw.c


#include<stdio.h>

#include<fcntl.h>

#include<unistd.h>

int main()

{

int fdr,fdw;

char temp[255];

char filepath[255];

char fileto[255];

printf("please input the filepath:");

scanf("%s",filepath);

if((fdr=open(filepath,O_RDONLY))==-1)

{

printf("file not found,open failed!");

return -1;

}

else

{

int r_size=read(fdr,temp,255);

close(fdr);

sprintf(fileto,"file-rw.txt");

if((fdw=open(fileto,O_WRONLY|O_CREAT,0640))==-1)

{

printf("open failed!");

return -1;

}

else

{

int w_size=write(fdw,temp,r_size);//相当于复制了所输入文件.txt中的255个大小的字符串到新文件file-rw.txt中

close(fdw);

printf("have successfully copied 255 chars from \"%s\" to \"%s\"\n",filepath,fileto);

}

}

return 0;

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值