使用C 从.TXT文件读取

Reading from a .txt file using class C++

本文关键字:文件 读取 TXT 使用      更新时间:2023-10-16

你能帮我吗?我是Truna,可以创建一个支持cmd-> int main(int argc, char *argv[])的程序。使用课程,我想创建一种写下我的不适的方法。.txt文件的名称是第三个参数。

我的问题是我需要open()我的文件,但是可以更改文件的名称。我尝试打开指定的文件,它的是1.txt。但是,我应该如何这样做才能在 cmd中给出文件的名称,因为我的方法(在 Header中,请参见该名称?

我的方法:

void recordData()
{
    wRecord.open("1.txt", std::ios_base::app);//the hard way to create a file in this method. 
    int i=0;
        wRecord  << "Name of your city: " << Name << std::endl;
        ......................................................
        wRecord  << "Quanity of schools in your city: " << Schools << std::endl;
        wRecord  << std::endl;
}

,我认为应该是wRecord.open(argv[3], std::ios_base::app);。但是如何正确提供argv[3]

我的代码,当我致电void recordData()

if (argv[1] == create)
    {
        wRecord.open(argv[3], std::ios_base::app);// here is I put any name of file
     //But I can't use any name because in method there is only `1.txt`
        if (!wRecord)
        {
            std::cerr << "Error: canNOT oprn a text file" << std::endl;
            exit(-1);
        }
    }

您应该在recorddata()函数中添加一个char*参数,以将其从main()argv []传递给wrecord.open()。

即:

void recordData(char *filename) 
{ 
    wRecord.open(filename, std::ios_base::app);
    ...
}