从命令行读取文本文件并将文件内容存储到c字符串中

时间:2014-10-06 01:44:30

标签: c++ command-line-arguments ifstream c-strings

我正在我的一个班级学习C ++,而且我很难将.txt文件的内容存储到c字符串中。

我已经弄清楚如何验证.txt文件是否存在,但是当我尝试将字符存储到c-string中时,它会崩溃。

这是我最近的尝试:

char * fileContent[MAX_SIZE];
ifstream ifile(argv[1]);
while (int i = 0 < MAX_SIZE)
{
    ifile >> fileContent[i];
    cout << fileContent[i];
    if (ifile.eof())
        break;
    i++;
}
ifile.close();

每次控制台进入循环时都会崩溃。是否有任何建议可以帮助实现这项目标?

我需要它是一个c字符串,以便我可以通过其他函数运行c-string。我还是C ++的新手。

赋值状态:&#34;将文本文件读入内存,一次一个字节&#34; 我希望我要做的就是这个。 谢谢

4 个答案:

答案 0 :(得分:0)

你的代码中有很少的bug,试试这个:

#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int MAX_SIZE = 128; 

int main(int argc, char* argv[])
{
    char fileContent[MAX_SIZE]; //bad idea never do that!
                                // use an std::vector<char> instead!
                                // and reverse a minimum amount of chars 
                                // using `reserve` if you are after performance
    ifstream ifile(argv[1]);
    int i = 0;
    while (i < MAX_SIZE)
    {
        ifile >> fileContent[i];
        cout << fileContent[i];
        if (ifile.eof())
            break;
        i++;
    }
    ifile.close();
}

答案 1 :(得分:0)

您可以使用以下代码从文本文件中读取并将字符串另存为C字符串。输出文件(output.txt)包含c-string输出。

#include <string>
#include <iostream>
#include <fstream>


int main()
{

    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);

    char *out_c_string;
    char ch;
    int index=0;

    while(cin >> ch)
        out_c_string[index++] = ch;


    for(int i=0; i<index; i++)
        cout << out_c_string[i]; // the c string of the file :)


    return 0;
}

答案 2 :(得分:0)

结合每个人的答案,我把它作为我的功能:

void get_file_info(char * argv, char (&fileContent) [MAX_SIZE], int & filesize ){
    freopen(argv, "r", stdin);
    char ch;
    int index = 0;

    while (cin >> noskipws >> ch)
        fileContent[index++] = ch;
    cout << endl << index << endl;

#if SHOW_DEBUG_CODE
    for (int count = 0; count < index; count++)
        cout << fileContent[count];
#endif

    fclose(stdin);
}

似乎工作得很好。我将在下一个空闲时间查看向量,但是现在,我将继续使用char数组。

感谢您的建议。

答案 3 :(得分:0)

我会这样做。处理任何大小的文件都比较通用。

void ReadFile(char*file,char**buff,int*size){

    // Open file as binary putting file position at the end
    ifstream is(file,ios::binary|ios::ate);

    // Get the current file position, which is the file end
    *size=is.tellg();

    // Put file pointer back at the start
    is.seekg(0,ios::beg);

    // errors
    if (!*size){
        cout<<"Unable to open input file or file empty\n";
        exit(9);
    }

    // allocate a buffer one bigger to allow for zero terminator
    *buff=new char[*size+1];

    // read the whole file in one hit
    is.read(*buff,*size);

    // Done. So close and zero delimit data.
    is.close();
    *(*buff+*size)=0;
}