首先要包含以下头文件
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>//以上文件操作需要头文件
#include<stdio.h>
#include<string.h>//strlen
#include<stdlib.h>//malloc
对于文件读写我们用read和write函数,与c中create函数类似,具体函数描述以及调用参数请自行参考百度
接下来是所有的代码
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int fd;
char *buf ="made by ck";
fd=open("./file1",O_RDWR);
if(fd ==-1)
{
printf("open file failed\n");
fd=open("./file1",O_RDWR|O_CREAT,0600);
if(fd>0)
{
printf("create file1 sucess\n");
}
}
printf("open sucess: fd=%d\n",fd);
int n_write =write(fd,buf,strlen(buf));
//这里注意不要用sizeof(buf),这样只会显示指针长度的字符数,例如在linux下指针长度为8字节,则文件中只输入了8个字节的字符。
if(n_write !=-1)
{
printf("write %d byte to file\n",n_write);
}
char *readBuf;
readBuf=(char*)malloc(sizeof(char)*n_write +1);
int n_read =read(fd,readBuf,n_write);
printf("read %d ,inside: %s\n",n_read,readBuf);
close(fd);
return 0;
}
然后会发现什么都读不到
原因是我们写完后 光标定位在字符最后,读取的时候是读取光标后面的东西,所以解决这个问题有两种方法
1.重新打开文件
2.重新定位光标
先来第一种,我们在写入完后,读取之前,进行关闭打开操作。
代码如下
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
#include<stdlib.h>
int main()
{
int fd;
char *buf ="made by ck";
fd=open("./file1",O_RDWR);
if(fd ==-1)
{
printf("open file failed\n");
fd=open("./file1",O_RDWR|O_CREAT,0600);
if(fd>0)
{
printf("create file1 sucess\n");
}
}
printf("open sucess: fd=%d\n",fd);
int n_write =write(fd,buf,strlen(buf));//don't use sizeof()
if(n_write !=-1)
{
printf("write %d byte to file\n",n_write);
}
close(fd);
fd=open("./file1",O_RDWR);
//重新关闭以及打开
char *readBuf;
readBuf=(char*)malloc(sizeof(char)*n_write +1);
int n_read =read(fd,readBuf,n_write);
printf("read %d ,inside: %s\n",n_read,readBuf);
close(fd);
return 0;
}
然后我们会看到正确的运行结果
接下来就是第二种方法
移动光标,我们知道
lseek这个函数的描述如下,包含三个参数w
of_t lseek(int fd,off_t offset,int whence)
我来进行简单翻译一下这三个参数,第一个是文件,第二个是偏移量,第三个是相对位置(文件头,文件当前位置,文件尾)
在我们写完代码后,我们处于文件尾,我们可以相对文件尾偏移(负)字符大小,也可以相对文件头偏移0,
头:SEEK_SET
尾:SEEK_END
当前位置:SEEK_CUR
就是在上述重新打开文件的相同位置更改为如下代码
lseek(fd,0,SEEK_SET);
运行结果如下
以上就是关于Linux下的简单文件读写操作,尚有不足之处,请大神指正
salute CLC