I am using the windows API in C++ and I want to get the content of a specific txt file. I contemplate using the ReadFile
function but I don' t know what I should use in place of HANDLE
or, in other words, how I should pass as parameter the name of the txt file. What is the best way generally to get the content of a txt file using windows API.
Asked
Active
Viewed 215 times
0

arjacsoh
- 8,932
- 28
- 106
- 166
-
possible duplicate of [Read whole ASCII file into C++ std::string](http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring) – Adriano Repetti Jul 03 '12 at 13:51
-
1Just to be sure, you _are_ aware that C++ has a standard API for files and most of the time you don't need to dig into WinAPI? – Kos Jul 03 '12 at 13:52
-
@Kos why should he if WinAPI is the best : ) – Agent_L Jul 03 '12 at 13:53
-
The best of what, of Windows APIs? :) – Kos Jul 03 '12 at 13:54
3 Answers
2
First, you must invoke CreateFile
("Creates or opens a file or I/O device"). It returns a handle which you subsequently pass to ReadFile
.
When you are done, don't forget to call CloseHandle.

Robᵩ
- 163,533
- 20
- 239
- 308
2
Use CreateFile()
, supplying GENERIC_READ
for the dwDesiredAccess
argument and OPEN_EXISTING
for the dwCreationDisposition
argument, to obtain a HANDLE
to pass to ReadFile()
.
Or, simpler, just use std::ifstream
:
#include <fstream>
#include <vector>
#include <string>
...
std::vector<std::sting> lines;
std::ifstream in("input.txt");
if (in.is_open())
{
std::string line;
while (std::getline(in, line)) lines.push_back(line);
}

hmjd
- 120,187
- 20
- 207
- 252