How do you open a file in C++?

后端 未结 9 865
-上瘾入骨i
-上瘾入骨i 2021-02-01 15:41

I want to open a file for reading, the C++ way. I need to be able to do it for:

  • text files, which would involve some sort of read line function.

相关标签:
9条回答
  • 2021-02-01 16:05
    #include <fstream>
    
    ifstream infile;
    infile.open(**file path**);
    while(!infile.eof())
    {
       getline(infile,data);
    }
    infile.close();
    
    0 讨论(0)
  • 2021-02-01 16:07

    There are three ways to do this, depending on your needs. You could use the old-school C way and call fopen/fread/fclose, or you could use the C++ fstream facilities (ifstream/ofstream), or if you're using MFC, use the CFile class, which provides functions to accomplish actual file operations.

    All of these are suitable for both text and binary, though none have a specific readline functionality. What you'd most likely do instead in that case is use the fstream classes (fstream.h) and use the stream operators (<< and >>) or the read function to read/write blocks of text:

    int nsize = 10;
    char *somedata;
    ifstream myfile;
    myfile.open("<path to file>");
    myfile.read(somedata,nsize);
    myfile.close();
    

    Note that, if you're using Visual Studio 2005 or higher, traditional fstream may not be available (there's a new Microsoft implementation, which is slightly different, but accomplishes the same thing).

    0 讨论(0)
  • 2021-02-01 16:13

    Follow the steps,

    1. Include Header files or name space to access File class.
    2. Make File class object Depending on your IDE platform ( i.e, CFile,QFile,fstream).
    3. Now you can easily find that class methods to open/read/close/getline or else of any file.
    CFile/QFile/ifstream m_file;
    m_file.Open(path,Other parameter/mood to open file);
    

    For reading file you have to make buffer or string to save data and you can pass that variable in read() method.

    0 讨论(0)
提交回复
热议问题