前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >记一次文件读写遇到的bug

记一次文件读写遇到的bug

作者头像
看、未来
发布2021-09-18 11:43:59
2040
发布2021-09-18 11:43:59
举报
文章被收录于专栏:CSDN搜“看,未来”

代码一:

代码语言:javascript
复制
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<iostream>
#include<unistd.h>

using namespace std;

int main(){
	char* buf = new char[8];	//can't alloc 1024?
	int fd = open("./fileIO.txt", O_CREAT|O_RDWR);
	
	if(fd<0){
		cout<<"open( file failed!)"<<endl;
	}

	return 0;
}

结果,创建出来的文件出现了很危险的权限,S和T、


代码2:

代码语言:javascript
复制
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<iostream>
#include<unistd.h>

using namespace std;

int main(){
	char* buf = new char[8];	//can't alloc 1024?
	int fd = open("./fileIO.txt", O_CREAT|O_RDWR);
	
	if(fd<0){
		cout<<"open( file failed!)"<<endl;
	}

	int m = write(fd,"test\n",5);
	cout<<m<<endl;

	int n = read(fd,buf,m);
	cout<<n<<endl;
	printf("%s\n",buf);
	close(fd);
	return 0;
}

结果:m有值,n为0,buf是确定是空的了。


后来,我觉得会不会是m是size_t的缘故,也只能死马当活马医了。

代码语言:javascript
复制
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<iostream>
#include<unistd.h>

using namespace std;

int main(){
	char* buf = new char[8];	//can't alloc 1024?
	int fd = open("./fileIO.txt", O_CREAT|O_RDWR);
	
	if(fd<0){
		cout<<"open( file failed!)"<<endl;
	}

	int m = write(fd,"test\n",5);
	cout<<m<<endl;
	
	int n = read(fd,buf,5);
	cout<<n<<endl;
	printf("%s\n",buf);
	close(fd);
	return 0;
}

嘿嘿,m/n都有值了,但是依旧buf没东西、 sizeof(buf) 也有长度,但是就没东西。


终于意识到,前面打开文件写入的时候,是重头覆盖,文件内容已经被覆盖,但是新的内容还没被保存,文件操作句柄在write,所以就导致了去读读不出内容来。

代码语言:javascript
复制
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<iostream>
#include<unistd.h>

using namespace std;

int main(){
	char* buf = new char[8];	//can't alloc 1024?
	int fd = open("./fileIO.txt", O_CREAT|O_RDWR);
	
	if(fd<0){
		cout<<"open( file failed!)"<<endl;
	}

	int m = write(fd,"test\n",5);
	cout<<m<<endl;
	close(fd);

	fd = open("./fileIO.txt", O_CREAT|O_RDWR);
	int n = read(fd,buf,5);
	cout<<n<<endl;
	printf("%s\n",buf);
	close(fd);
	return 0;
}

这样呢?

代码语言:javascript
复制
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<iostream>
#include<unistd.h>

using namespace std;

int main(){
	char* buf = new char[8];	//can't alloc 1024?
	fd = open("./fileIO.txt", O_CREAT|O_RDWR|O_APPEND);
	
	if(fd<0){
		cout<<"open( file failed!)"<<endl;
	}

	int m = write(fd,"test\n",5);

	int n = read(fd,buf,5);
	cout<<n<<endl;
	printf("%s\n",buf);
	close(fd);
	return 0;
}

不好使啊,还是那句话啊,还没存回去呢。


从这个记录中,可以推出文件读写的流程来: 打开文件,获取句柄; 将文件内容写入缓冲区操作,此刻文件内部空虚; 关闭文件,将缓冲区内新文件内容写回。 可进行下一步操作。

所以,记得关掉。 还有,读取的时候,记得换行,刷新缓冲区。


本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/08/07 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档