从现在开始,进行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移动文件指针即可,向里面写,即可