你如何在C ++中获得文件?

时间:2009-03-07 06:28:37

标签: c++ file io

所以老师提出了这个任务:

您已被联合网络执法司令部聘用,并且您已获得包含您必须解密的空密码的文件。

因此对于给出的第一个文件(作为示例),每隔一个字母都是正确的(即:'hielqlpo'是你好的(假设你从第一个字母开始)。我的第一个问题是,我如何读取文件?文档在我的桌面上的文件夹中,文件名为document01.cry。我不确定将该文件放入程序的命令。

我也不太确定如何抓住一封信并跳过一封信,但说实话,我想在发布这个问题之前修补它!所以现在...我的问题如标题所述:你如何获取一个用C ++阅读的文件?

如果它有所作为(我确信它确实如此),我正在使用Visual C ++ 2008 Express Edition(因为它是免费的,我喜欢它!我还附上了我迄今为止的内容,请保留记住它是非常基本的...我在最后添加getchar();所以当它运行正常时,窗口保持打开状态,所以我可以看到它(因为Visual Express倾向于关闭窗口,因为它是跑完了。)

到目前为止的代码:

#include<iostream>

using namespace std;

int main()
{
    while (! cin.eof())
    {
        int c = cin.get() ;
        cout.put(c) ;
    }
    getchar();
}

PS:我意识到这段代码会抓住每一个角色。现在这很好,一旦我可以阅读文件,我想我可以从那里修补它。我也在盯着我在C ++上看到的一两本书,看看它弹出的任何东西,尖叫着“接我!”再次感谢!

编辑::也好奇,有没有办法输入你想要的文件? (即:

char filename;
cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
cin >> filename;
cout << endl;
ifstream infile(filename, ios::in);

此代码不起作用。它发回一个错误,说char不能转换为const char *。如何解决这个问题?

编辑2: 没关系说第2部分,我发现了!再次感谢您的帮助!

5 个答案:

答案 0 :(得分:9)

要进行文件操作,您需要正确的include:

#include <fstream>

然后,在您的main函数中,您可以打开文件流:

ifstream inFile( "filename.txt", ios::in );

或者,对于输出:

ofstream outFile( "filename.txt", ios::out );

然后您可以使用inFile,就像使用cin一样,使用outFile就像使用cout一样。完成后关闭文件:

inFile.close();
outFile.close();

答案 1 :(得分:3)

答案 2 :(得分:3)

[EDIT]包括对命令行参数的支持 [编辑]修复了可能的内存泄漏 [编辑]修正了遗失的参考资料

#include <fstream>
#include <iostream>

using namespace std;

int main(int argc, char *argv){
    ifstream infh;  // our file stream
    char *buffer;

    for(int c = 1; c < argc; c++){
        infh.open(argv[c]);

        //Error out if the file is not open
        if(!infh){
            cerr << "Could not open file: "<< argv[c] << endl;
            continue;
        }

        //Get the length of the file 
        infh.seekg(0, ios::end);
        int length = infh.tellg();

        //reset the file pointer to the beginning
        is.seekg(0, ios::beg);

        //Create our buffer
        buffer = new char[length];

        // Read the entire file into the buffer
        infd.read(buffer, length);

        //Cycle through the buffer, outputting every other char
        for(int i=0; i < length; i+= 2){
            cout << buffer[i]; 
        }
        infh.close();
    }
    //Clean up
    delete[] buffer;
    return 0;
}

应该做的伎俩。如果文件非常大,您可能不应该将整个文件加载到缓冲区中。

答案 3 :(得分:1)

我明白了!说实话,没有人帮忙,这是三者的结合,加上他们的评论。非常感谢你们!我附上了我使用的代码,以及该文档的副本。程序读入每个字符,然后吐出解密的文本。 (IE:1h.e0l / lqo是你好)下一步(额外功劳)是设置它,以便用户输入要读取的下一个字符之前要跳过的字符数。

这一步我打算自己做,但再次,非常感谢大家的帮助!再次证明这个网站有多棒,一次只有一行代码!

编辑::代码调整为接受用户输入,以及允许多次使用而无需重新编译(我意识到它看起来像一个巨大的草率混乱,但这就是为什么它非常评论...因为在我看来它看起来不错,纯)

#include<iostream>
#include<fstream>   //used for reading/writing to files, ifstream could have been used, but used fstream for that 'just in case' feeling.
#include<string>    //needed for the filename.
#include<stdio.h>   //for goto statement

using namespace std;

int main()
{
    program:
    char choice;  //lets user choose whether to do another document or not.
    char letter;  //used to track each character in the document.
    int x = 1;    //first counter for tracking correct letter.
    int y = 1;    //second counter (1 is used instead of 0 for ease of reading, 1 being the "first character").
    int z;        //third counter (used as a check to see if the first two counters are equal).
    string filename;    //allows for user to input the filename they wish to use.
    cout << "Please make sure the document is in the same file as the program, thank you!" << endl << "Please input document name: " ;
    cin >> filename; //getline(cin, filename);
    cout << endl;
    cout << "'Every nth character is good', what number is n?: ";
    cin >> z;   //user inputs the number at which the character is good. IE: every 5th character is good, they would input 5.
    cout << endl;
    z = z - 1;  //by subtracting 1, you now have the number of characters you will be skipping, the one after those is the letter you want.
    ifstream infile(filename.c_str()); //gets the filename provided, see below for incorrect input.
    if(infile.is_open()) //checks to see if the file is opened.
    {
        while(!infile.eof())    //continues looping until the end of the file.
        {   
                infile.get(letter);  //gets the letters in the order that that they are in the file.
                if (x == y)          //checks to see if the counters match...
                {
                    x++;             //...if they do, adds 1 to the x counter.
                }
                else
                {
                    if((x - y) == z)            //for every nth character that is good, x - y = nth - 1.
                    {
                        cout << letter;         //...if they don't, that means that character is one you want, so it prints that character.
                        y = x;                  //sets both counters equal to restart the process of counting.
                    }
                    else                        //only used when more than every other letter is garbage, continues adding 1 to the first
                    {                           //counter until the first and second counters are equal.
                        x++;
                    }
                }
        }
        cout << endl << "Decryption complete...if unreadable, please check to see if your input key was correct then try again." << endl;
        infile.close();
        cout << "Do you wish to try again? Please press y then enter if yes (case senstive).";
        cin >> choice;
        if(choice == 'y')
        {
            goto program;
        }
    }
    else  //this prints out and program is skipped in case an incorrect file name is used.
    {
        cout << "Unable to open file, please make sure the filename is correct and that you typed in the extension" << endl;
        cout << "IE:" << "     filename.txt" << endl;
        cout << "You input: " << filename << endl;
        cout << "Do you wish to try again? Please press y then enter if yes (case senstive)." ;
        cin >> choice;
        if(choice == 'y')
        {
            goto program;
        }
    }
    getchar();  //because I use visual C++ express.
}

EDIT :::

我尝试插入文本,但我无法让它出来正确,它一直在处理一些像编码的字符(即撇号显然相当于粗体命令),但你可以尝试放置在“0h1e.l9lao”中没有括号到.txt,它应该给出相同的结果。

再次感谢大家的帮助!

答案 4 :(得分:1)

虽然你的问题得到了回答,但有两个小提示: 1)您可以执行以下操作,而不是计算x和y以查看您是否处于奇数或偶数字符:

int count=0;
while(!infile.eof())
{       
    infile.get(letter);
    count++;
    if(count%2==0)
    {
        cout<<letter;
    }
}

%实质上意味着'除以时的余数',因此11%3是2。在上面它给出奇数或偶数。

2)假设您只需要在Windows上运行它:

system("pause");

会使窗口在完成运行时保持打开状态,因此您不需要最后一次getchar()调用(为了实现这一点,您可能需要#include<Windows.h>)。