文件未在C++中打开

File not opening in C++

本文关键字:C++ 文件      更新时间:2023-10-16

文件没有打开我犯了什么错误。输出屏幕显示无法打开文件。如果我分别创建 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::truncios::app,具体取决于您是要重写还是追加文件,否则如果它不存在,则不会创建它:

file.open("text.txt", ios::trunc | ios::in | ios::out | ios::binary);

请注意,ios::ateios::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);

相反