天天看点

记一次文件读写遇到的bug

代码一:

#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:

#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的缘故,也只能死马当活马医了。

#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,所以就导致了去读读不出内容来。

#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;
}
           

这样呢?

#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;
}
           

继续阅读