一个基础的文件读写(复习)

来源:互联网 发布:毕加索美工钢笔推荐 编辑:程序博客网 时间:2024/06/06 02:15
 //一个基础的文件读写,(由于上传原因,代码的格式不太好,仅供参考,代码编写测试均成功,仅供参考)


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

    int main(int argc,char *argv[])
     {
 int fd=-1;
        int ret=-1;
        char buf[100]={0}; 
        char writebuf[20]="I LOVE Linux";


     //第一步:打开一个文件

 

         fd=open("a.txt",O_RDWR);

    
 if(fd<0)
           {

    perror("文件打开错误.\n");

   return(-1);

   }
 else
    printf("fd=%d.\n",fd);
  //第二步:读写文件
/*     
//读文件

 ret= read(fd,buf,6);
       
  if(ret<0)
   {

printf("文件读取失败.\n");

_exit(-1);

   } 
          else
                printf("文件读取成功,文件读取字节数为%d.\n",ret);
                printf("读取的内容为:[%s].\n",buf);  
*/

//写文件

  ret=write(fd,writebuf,strlen(writebuf));
  if(ret<0)
     {

printf("写文件失败.\n");

_exit(-1);

     } 
           else
                printf("文件写成功,写入了%d个字节.\n",ret);  


     //第三步:关闭文件
    close(fd);
 
    return 0;
 
}
0 0