linux C++ 读写文件
来源:互联网 发布:php 访问者模式 编辑:程序博客网 时间:2024/06/08 02:37
从现在开始,进行linux的学习了,开始呢,总想着,windows下的C++已经很熟悉了,所以呢,linux'下的c编程,应该就很快上手,上来就不应该从0开始了,可渐渐发现,根本不是这样的,即使是一个简单的文件读写操作,也使用了很长时间,呵呵,眼高手低阿,不过,还是很有收获的,慢慢来吧,还有时间,学习!学习
恩就这样吧,
#include<cstring>#include<unistd.h>#include<errno.h>#include<fcntl.h>#include<iostream>using namespace std;int main(){ //open the file if not process exit and output the err message char* fileName="hehe.txt"; int fileDes=open(fileName,O_CREAT|O_RDWR|O_APPEND,0666);// we need the file fcntl.h if(fileDes==-1) { cout<<"the file open failed with the code : "<<errno<<endl; //we need the errno.h return 0; } cout<<"the file open success\n"; //first we need to read the file content and then output to the screen after that write the time int fileSize=lseek(fileDes,0,SEEK_END)+1; lseek(fileDes,0,fileSize); char buf[1024]={0}; while(read(fileDes,buf,1024)>0)//read we need the file unistd.h { cout<<buf<<endl; } strcpy(buf,"\nthis is a other day\n"); if(write(fileDes,buf,strlen(buf))==-1)// write we need the file unistd.h strlen need the file cstring { cout<<"write file error with the code :"<<errno<<endl; } close(fileDes);//close we need the file unistd.h}
这里面需要注意的是,如果没有文件则建立新的文件,就要使用O_CREAT,但是呢,仅仅使用这个参数,只是确定了文件的新建操作,而读写还要设定O_RDWR.可读可写才行,否则会出现write错误 errno代码是9,
再有获得文件大小是(fileDes,0,SEEK_END)+1,这样就获得了文件的大小,再使用lseek移动文件指针即可,向里面写,即可
0 0
- Linux C 读写文件
- Linux C语言文件读写
- Linux C 简单低级文件读写(1)
- Linux下C 文件读写程序
- Linux与C语言的文件读写
- 【C/C++】文件读写
- Linux C编程(3) 使用C语言函数读写文件
- c语言读写文件
- 文件读写(c)
- C#-读写INI文件
- [C++]文件读写操作
- C#读写INI文件
- C 读写文件
- C读写ini文件
- c#FileStream文件读写
- 读写文件 c
- WinAPI C读写文件?
- C语言读写文件
- [笔记]VS2010 LNK1123: 转换到 COFF 期间失败: 文件无效或损坏 的解决方法
- Java老学员重回广州传智,大方传授面试经验
- 我在博看文思学习生活
- 编译libcurl
- andriodpn整合改进源码
- linux C++ 读写文件
- 第二次试验--算法基本功和综合思考
- 软件测试策略之确认测试(Validation Testing)和系统测试(System Testing)
- hdu 1567 2006
- svn 相關經驗 svn checkout with commit times (keep original timestamp)
- s3c2410 MMU(存储器管理单元)讲解
- Light 1289 LCM from 1 to n 素数筛选位优化
- 文字滚动后自动停止的特效
- 第1次实验——NPC问题(回溯算法、聚类分析)