文件未在C++中打开
File not opening in C++
文件没有打开我犯了什么错误。输出屏幕显示无法打开文件。如果我分别创建 ofstream 和 ifstream 构造函数,则文件被正确写入和读取。如果我在下面使用 fstream,则不会创建文件。
#include <iostream>
#include <fstream>
using namespace std;
void main(){
char num[10];
fstream file;
file.open("text.txt", ios::ate|ios::in|ios::out| ios::binary);
if (!file)
{
cerr << "File could not be opened" << endl;
exit(1);
} // End if
for (int i = 0; i <= 5; i++){
cout << "Enter an integer " << endl;
cin >> num[i]; //Input a number
file.write((char*)num, sizeof(num)); //Function write to write data to file
}
for (int i = 0; i <= 5; i++){
file.read((char*)num, sizeof(num)); //Function to read data from the file
cout << endl << num[i] << " ";
}
file.close();
system("pause");
}
您应该指定ios::trunc
或ios::app
,具体取决于您是要重写还是追加文件,否则如果它不存在,则不会创建它:
file.open("text.txt", ios::trunc | ios::in | ios::out | ios::binary);
请注意,ios::ate
与ios::trunc
结合使用没有意义,因为文件被截断。
您还可以查看ios
标志和等效stdio
模式字符串之间的对应表。如您所见,当前代码的表的相应行是
模式字符串 openmode & ~ate 如果文件已存在,则操作 如果文件不存在,则执行操作"r+b" 二进制|输出|输入 从开始读取错误
PS:并且不要忘记将void main()
更改为int main()
,因为前者是未定义的行为。
更新:是的,你的整个写作和阅读代码都是错误的。它应该重写如下:
for (int i = 0; i <= 5; i++){
cout << "Enter an integer " << endl;
cin >> num[i]; //Input a number
}
// write the array once and outside of the loop
file.write((char*)num, sizeof(num));
// not necessary - just to ensure we read numbers in the next lines
memset(num, 0, sizeof(num));
// go to the beginning of the file
file.seekg(0);
// read the array once and outside of the loop
file.read((char*)num, sizeof(num));
for (int i = 0; i <= 5; i++){
cout << endl << num[i] << " ";
}
演示
您应该将"ios::out"添加到您的文件中。
file.open("text.txt", ios::out);
您还可以使用 检查文件是否更容易打开
if (!file.is_open())
编辑:
可能该组合无效。尝试使用
file.open("text.txt", ios::app|ios::out|ios::in|ios::binary);
相反
相关文章:
- .cpp和.h文件中的模板专用化声明
- 为什么两个不同的未命名名称空间可以共存于一个cpp文件中
- 文本文件中的单词链表
- CMake-按正确顺序将项目与C运行时对象文件链接
- 使用新行和不使用新行读取文件
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 挂起和取消挂起一个文件DLL
- 如何确定我已使用非编码文件到达 EOF?
- 命名空间中具有.h和.cpp文件的类
- 如何使用ndk-build.cmd构建Android.so文件
- 从包含m行的文件中提取n行,必要时(惰性地)重复该文件
- 读取文件并输入到矢量中
- 在C++中查找文件
- c++库的公共头文件中应该包含什么
- 用c++从输入文件中读取另一行
- Cppcheck生成xml转储文件
- 读取文件的最后一行并输入到链接列表时出错
- 无法编译 rtmidi 测试 cmidiin.cpp 文件, 非法指令
- 如何将内容数组写入文本文件?
- C++ Windows 驱动程序MSB3030无法复制该文件,因为它找不到