无法在一个.dat文件中读取以创建第二个.dat文件

时间:2017-03-03 06:35:32

标签: c++ file-io

尝试使用while循环读取一个文件(它被称为" Stocks.dat"以及我使用while循环的原因是因为将来X可以附加库存量;下面列出.dat文件的格式)以创建第二个文件" profits.dat"其中包含" Stocks.dat"的信息。但随着新的计算浮动。这个运行很好,但当我检查是否" profits.dat"存在,那里什么都没有。为什么我没有获得" profit.dat"包含所有计算的文件?非常感谢。

#include<iostream>
#include<fstream> 
using namespace std;

int main()
{
    char name[40];
    int sh;
    float pp, cp, pc, cv, pr;

    ifstream infile("c:\\Stocks.dat", ios::in);
    ofstream outfile("c:\\profits.dat", ios::out);


    while (infile.getline(name, 40)) //don't forget the whitespace
    {
    infile >> sh >> pp >> cp;
    pc = sh * pp;
    cv = sh * cp;
    pr = cv - pc;
    outfile << name << endl; //need the endline
    outfile << pc << ' ' << cv << ' ' << pr << ' ' << endl; //need the blank spaces
    infile.ignore(40, '\n');
    }

    infile.close();
    outfile.close();

    return 0;
}

//Stocks.dat information:
//APPLE
//500 20.25 30.75
//MICROSOFT
//250 9.75 12.99
//GOOGLE
//1000 50.10 300.85

1 个答案:

答案 0 :(得分:1)

很可能是权限问题。您的ofstream无法在位置C:打开文件进行写入 - 直接写入您的系统驱动器需要管理员权限(我认为从Windows Vista开始,但我不确定)。

您可以以管理员身份运行程序,也可以在可以编写的位置放置文件(更改路径作为写入的开头创建文件)。

修改

更改此

ofstream outfile("c:\\profits.dat", ios::out);

到这个

ofstream outfile("c:\\users\\YOUR_USER\\desktop\\profits.dat", ios::out);

或您可以在没有管理员权限的情况下编写的其他位置。您可以通过打开notepad并尝试保存文件来找到此类位置。如果您可以在该位置保存文件,您的程序将成功创建profits.dat