当前位置: 移动技术网 > IT编程>开发语言>C/C++ > new与new(std::nothrow)在文件操作上内存分布上有区别吗?

new与new(std::nothrow)在文件操作上内存分布上有区别吗?

2020年08月05日  | 移动技术网IT编程  | 我要评论
各位大佬好,我最近在学习C++文件操作上seekp() 来进行文件指针的移动,我想用seekp()去修改文件中指定的数据(我用了结构体类型的数据)用write()函数进行写入数据到文件,然后用read()函数读取到一个结构体的指针上-----在用new分配内存时,我使用了new(std::nothrow)分配(因为后面我用NULL判断是否成功),然后赋值输出,输出的结果不正确,但是我将new(std::nothrow)中的std::nothrow删除后又成功了???我想问一下各位大佬,这是为什么?是因为n

最近在学习C++文件操作上seekp() 来进行文件指针的移动,我想用seekp()去修改文件中指定的数据(我用了结构体类型的数据)用write()函数进行写入数据到文件,然后用read()函数读取到一个结构体的指针上-----在用new分配内存时,我使用了new(std::nothrow)分配(因为后面我用NULL判断是否成功),然后赋值输出,输出的结果不正确,但是我将new(std::nothrow)中的std::nothrow删除后又成功了???
我想问一下各位大佬,这是为什么?是因为new与new(std::nothrow)在分配内存时不大一样吗?为什么删除std::nothrow后又成功了?

代码如下:

#include<iostream> #include<fstream> #include<cstdlib> using std::ios; using std::fstream; using std::ifstream; using std::ofstream; using std::cout; using std::cerr; using std::cin; using std::endl; struct Person { int id; char *name; }; int main() { struct Person person[]={{100,"YHY"},{101,"HCX"},{102,"YYC"},{103,"YJX"},{104,"LST"}}; int N=sizeof(person)/sizeof(Person); //打开文件 ofstream outfile("人事管理.txt",ios::out|ios::trunc); if(!outfile.is_open()) { cerr<<"Open File Error  -ofstream"<<endl; system("pause"); exit(1); } //对文件进行写入操作 for(int i=0;i<N;i++) { ***outfile.write((char*)(&person[i]),sizeof(Person));*** //使用write()   进行写入  因为是二进制文件  所以在文件中是乱码形式  在写一个read()函数 } //关闭文件 outfile.close(); //数据修改 outfile.open("人事管理.txt",ios::out|ios::in); if(!outfile.is_open()) { cerr<<"Open File Error  -ofstream"<<endl; system("pause"); exit(1); } person[N-2].id=105; person[N-2].name="tom"; outfile.seekp((N-2)*(sizeof(Person)),ios::beg); //用seekp()   定位到要修改文件的位置 outfile.write((char*)(&person[N-2]),sizeof(Person)); //写入 outfile.close(); //读取文件中的内容 ifstream infile("人事管理.txt",ios::in); if(!infile.is_open()) { cerr<<"Open File Error   -ifstream"<<endl; system("pause"); exit(1); } 

//在这里我用了一个Person类的指针然后动态分配内存
//在这里把std::nothrow删了后,程序正常运行 但是不删去后面读取文件时就会错误?

 //在这里我用了一个Person类的指针然后动态分配内存 Person *persons=new/*(std::nothrow)*/ Person[N]; //在这里把std::nothrow删了后,程序正常运行  但是不删去后面读取文件时就会错误 if(person==NULL) { cerr<<"Share Memory Error  -new"<<endl; system("pause"); exit(1); } for(int i=0;i<N;i++) { infile.read((char*)(&persons[i]),sizeof(Person)); cout<<persons[i].id<<"\t"<<person[i].name<<endl; } delete[] persons; infile.close(); system("pause"); return 0; 

我用的是VS2010的编辑器,如果有什么不对的,欢迎指正。

本文地址:https://blog.csdn.net/YHY_1983127442/article/details/107774758

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网