简体   繁体   English

如何在 C++ 中获取文件?

[英]How do you get a file in C++?

So the teacher has posed this assignment:所以老师布置了这个作业:

You have been hired by the United Network Command for Law Enforcement, and you have been given files containing null cyphers you have to decrypt.您已受雇于执法联合网络司令部,并且您已获得包含 null 密码的文件,您必须对其进行解密。

So for the first file given (as an example), every other letter is correct (ie: 'hielqlpo' is hello (assuming you start with the first letter). My first question is, how do I read in a file? The document is on my desktop in a folder and the file is named document01.cry. I'm not sure the command I need to put that file into the program.因此,对于给出的第一个文件(例如),其他每个字母都是正确的(即:'hielqlpo' 是 hello(假设您从第一个字母开始)。我的第一个问题是,我如何读取文件?文档在我桌面上的一个文件夹中,文件名为 document01.cry。我不确定将文件放入程序所需的命令。

I'm also not overly sure how to grab a letter and skip a letter, but honestly I want to tinker with that before I post that question.我也不太确定如何抓住一封信并跳过一封信,但老实说,我想在发布那个问题之前修改一下。 So for now..:my question is as stated in the title?所以现在..:我的问题如标题所述? How do you grab a file for reading in C++?您如何获取文件以在 C++ 中读取?

If it makes a difference (As I'm sure it does), I'm using Visual C++ 2008 Express Edition (because it's free and I like it, I've also attached what I have so far. please keep in mind it's -very- basic...and I added the getchar(); at the end so when it does run properly, the window stays open so I can see it (as Visual Express tends to close the window as soon as it's done running.)如果它有所作为(我确信它确实如此),我正在使用 Visual C++ 2008 Express Edition(因为它是免费的而且我喜欢它,我还附上了我到目前为止所拥有的东西。请记住它是 -非常基本...我在最后添加了getchar();因此,当它正常运行时,window 保持打开状态,因此我可以看到它(因为 Visual Express 倾向于在 window 运行完成后立即关闭它。)

The code so far:到目前为止的代码:

#include<iostream>

using namespace std;

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

PS: I realize that this code grabs and puts out every character. PS:我意识到这段代码抓取并输出了每个字符。 For now that's fine, once I can read in the file I think I can tinker with it from there.现在这很好,一旦我可以读取文件,我想我可以从那里修改它。 I'm also poking at a book or two I have on C++ to see it anything pops up and screams "Pick me!"我还在看我在 C++ 上的一两本书,看到它弹出任何东西并尖叫“选我!” Thanks again!再次感谢!

EDIT:: Also curious, is there a way to input the file you want?编辑:: 也很好奇,有没有办法输入你想要的文件? (Ie: (IE:

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);

This code doesn't work.此代码不起作用。 It shoots back an error saying the char can't be converted to a const char *.它返回一个错误,说 char 不能转换为 const char *。 How can this problem be fixed?如何解决这个问题?

EDIT 2: Never mind about said part 2, I found it out!编辑 2:不要介意所说的第 2 部分,我发现了! Thanks again for the assistance!再次感谢您的帮助!

To do file operations, you need the correct include:要进行文件操作,您需要正确的包括:

#include <fstream>

Then, in your main function, you can open a file stream:然后,在你的主 function 中,你可以打开一个文件 stream:

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

or, for output:或者,对于 output:

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

You can then use inFile as you would use cin, and outFile as you would use cout.然后,您可以像使用 cin 一样使用 inFile,也可以像使用 cout 一样使用 outFile。 To close the file when you are done:完成后关闭文件:

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

[EDIT] include support for command line arguments [EDIT] Fixed possible memory leak [EDIT] Fixed a missing reference [编辑] 包括对命令行 arguments 的支持 [编辑] 修复了可能的 memory 泄漏 [编辑] 修复了缺少的参考

#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;
}

Should do the trick.应该做的伎俩。 If the file is extremely large, you probably shouldn't load the entire file into the buffer.如果文件非常大,您可能不应该将整个文件加载到缓冲区中。

I figured it out, To be honest no one answer helped, it was a combination of the three.我想通了,说实话,没有一个答案有帮助,这是三者的结合。 plus the comments from them, Thank you all very much.加上他们的评论,非常感谢大家。 I've attached the code I used, as well as a copy of the document.我附上了我使用的代码以及文档的副本。 The program reads in every character: then spits out the deciphered text.程序读入每个字符:然后吐出破译的文本。 (IE. 1h.e0l/lqo is hello) The next step (extra credit) is to set it up so the user inputs how many characters to skip before reading in the next character to input. (IE. 1h.e0l/lqo 是你好)下一步(额外功劳)是设置它,以便用户在读取下一个要输入的字符之前输入要跳过的字符数。

This step I intend to do on my own, but again, thank you very much for all the assistance everyone, Proving once again how awesome this site is, one line of code at a time!这一步我打算自己做,但再次感谢大家的帮助,再次证明这个网站有多棒,一次一行代码!

EDIT:: Code adjusted to accept user input, as well as allow for multiple uses without recompiling (I realize it looks like a huge sloppy mess, but that's why it's EXTREMELY commented...because in my mind it looks nice and neat)编辑:: 代码调整为接受用户输入,并允许在不重新编译的情况下多次使用(我意识到它看起来像一个大杂烩,但这就是为什么它被极度评论......因为在我看来它看起来很漂亮和整洁)

#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:::编辑:::

I tried inserting the text, but I couldn't get it to come out right, it kept treating some of the characters like coding (ie an apostrophe apparently is the equivalent of the bold command), but you could just try putting in "0h1e.l9lao" without the parenthesis into a.txt and it should give the same outcome.我尝试插入文本,但无法正确显示,它一直处理一些字符,如编码(即撇号显然相当于粗体命令),但你可以尝试输入“0h1e .l9lao" 不带括号到 a.txt 中,它应该给出相同的结果。

Thanks again everyone for the help!再次感谢大家的帮助!

Although your queston has been answered, two little tips: 1) Instead of counting x and y to see if you are on an odd or even character you can do the following:尽管您的问题已得到解答,但有两个小提示:1)您可以执行以下操作,而不是计算 x 和 y 来查看您是在奇数还是偶数字符上:

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

% essentially means 'remainder when divided by,' so 11%3 is two. % 基本上意味着“除以时的余数”,所以 11%3 是二。 in the above it gives odd or even.在上面它给出了奇数或偶数。

2) Assuming you only need to run it on windows: 2)假设您只需要在windows上运行它:

system("pause");

will make the window stay open when its finished running so you don't need the last getchar() call (you may have to #include<Windows.h> for that to work).将使 window 在其完成运行后保持打开状态,因此您不需要最后一次 getchar() 调用(您可能需要#include<Windows.h>才能使其工作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM