簡體   English   中英

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

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

所以老師布置了這個作業:

您已受雇於執法聯合網絡司令部,並且您已獲得包含 null 密碼的文件,您必須對其進行解密。

因此,對於給出的第一個文件(例如),其他每個字母都是正確的(即:'hielqlpo' 是 hello(假設您從第一個字母開始)。我的第一個問題是,我如何讀取文件?文檔在我桌面上的一個文件夾中,文件名為 document01.cry。我不確定將文件放入程序所需的命令。

我也不太確定如何抓住一封信並跳過一封信,但老實說,我想在發布那個問題之前修改一下。 所以現在..:我的問題如標題所述? 您如何獲取文件以在 C++ 中讀取?

如果它有所作為(我確信它確實如此),我正在使用 Visual C++ 2008 Express Edition(因為它是免費的而且我喜歡它,我還附上了我到目前為止所擁有的東西。請記住它是 -非常基本...我在最后添加了getchar();因此,當它正常運行時,window 保持打開狀態,因此我可以看到它(因為 Visual Express 傾向於在 window 運行完成后立即關閉它。)

到目前為止的代碼:

#include<iostream>

using namespace std;

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

PS:我意識到這段代碼抓取並輸出了每個字符。 現在這很好,一旦我可以讀取文件,我想我可以從那里修改它。 我還在看我在 C++ 上的一兩本書,看到它彈出任何東西並尖叫“選我!” 再次感謝!

編輯:: 也很好奇,有沒有辦法輸入你想要的文件? (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);

此代碼不起作用。 它返回一個錯誤,說 char 不能轉換為 const char *。 如何解決這個問題?

編輯 2:不要介意所說的第 2 部分,我發現了! 再次感謝您的幫助!

要進行文件操作,您需要正確的包括:

#include <fstream>

然后,在你的主 function 中,你可以打開一個文件 stream:

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

或者,對於 output:

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

然后,您可以像使用 cin 一樣使用 inFile,也可以像使用 cout 一樣使用 outFile。 完成后關閉文件:

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

[編輯] 包括對命令行 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;
}

應該做的伎倆。 如果文件非常大,您可能不應該將整個文件加載到緩沖區中。

我想通了,說實話,沒有一個答案有幫助,這是三者的結合。 加上他們的評論,非常感謝大家。 我附上了我使用的代碼以及文檔的副本。 程序讀入每個字符:然后吐出破譯的文本。 (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.
}

編輯:::

我嘗試插入文本,但無法正確顯示,它一直處理一些字符,如編碼(即撇號顯然相當於粗體命令),但你可以嘗試輸入“0h1e .l9lao" 不帶括號到 a.txt 中,它應該給出相同的結果。

再次感謝大家的幫助!

盡管您的問題已得到解答,但有兩個小提示:1)您可以執行以下操作,而不是計算 x 和 y 來查看您是在奇數還是偶數字符上:

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

% 基本上意味着“除以時的余數”,所以 11%3 是二。 在上面它給出了奇數或偶數。

2)假設您只需要在windows上運行它:

system("pause");

將使 window 在其完成運行后保持打開狀態,因此您不需要最后一次 getchar() 調用(您可能需要#include<Windows.h>才能使其工作)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM