Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you open a file in C++?

Tags:

c++

file

io

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.

  • binary files, which would provide a way to read raw data into a char* buffer.

like image 930
andrewrk Avatar asked Aug 11 '08 15:08

andrewrk


People also ask

How can I open file in C?

Opening a file is performed using the fopen() function defined in the stdio. h header file. The syntax for opening a file in standard I/O is: ptr = fopen("fileopen","mode");

How a file is opened and closed in C?

C provides a number of build-in function to perform basic file operations: fopen() - create a new file or open a existing file. fclose() - close a file. getc() - reads a character from a file.

How do files work in C?

For C File I/O you need to use a FILE pointer, which will let the program keep track of the file being accessed. For Example: FILE *fp; To open a file you need to use the fopen function, which returns a FILE pointer.


2 Answers

You need to use an ifstream if you just want to read (use an ofstream to write, or an fstream for both).

To open a file in text mode, do the following:

ifstream in("filename.ext", ios_base::in); // the in flag is optional 

To open a file in binary mode, you just need to add the "binary" flag.

ifstream in2("filename2.ext", ios_base::in | ios_base::binary );  

Use the ifstream.read() function to read a block of characters (in binary or text mode). Use the getline() function (it's global) to read an entire line.

like image 103
Derek Park Avatar answered Oct 07 '22 16:10

Derek Park


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; std::vector<char> somedata(nsize); ifstream myfile; myfile.open("<path to file>"); myfile.read(somedata.data(), 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).

like image 25
DannySmurf Avatar answered Oct 07 '22 14:10

DannySmurf