How can I read file at certain path?

[Closed by author]
Last edited on
C++17's filesystem library would be a logical choice.
https://en.cppreference.com/w/cpp/filesystem
My actual problem is that I want to use std::getline(std::ifstream, std::string) to
read the file line by line... How can I do this with a file at a certain path?
Backslashes in string literals must be escaped with a backslash, as in
"C:\\file.txt"
In the example your provided, the string literal "C:\file.txt" contains FORM FEED (not a backslash) as the character at offset 2.

Prefer to just use forward slashes for path names. This is more consistent with other systems and less error-prone:
"C:/file.txt"

Sorry, I knew that, but I tried C:\\file.txt a while back and
I don't remember it working. Are you saying forward slashes will work?
Are you saying forward slashes will work?
No.

C:/file.txt refers to the same file as C:\\file.txt. Since you found the latter doesn't work, the former won't either.

Your next step is to write some code to diagnose the problem. For instance, you can run this code and see what it says:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <fstream>
#include <cstdio>
#include <cerrno>
#include <cassert>

#include <windows.h>

int main()
{
  char const* file_name = "C:/file.txt";
    
  std::printf("attempting to open file name %s\n", file_name);  
  std::fflush(stdout);
  
  if (std::ifstream os{file_name})
    std::puts("success");
  else
  {
    // Here's what the C API has to say:
    std::perror("error");
      
    // Here's what the Windows API has to say:
    DWORD const last_error = GetLastError();
    DWORD const fmtflags = 
      FORMAT_MESSAGE_FROM_SYSTEM    | FORMAT_MESSAGE_IGNORE_INSERTS |
      FORMAT_MESSAGE_ARGUMENT_ARRAY | FORMAT_MESSAGE_ALLOCATE_BUFFER;
    
    LPWSTR msg = nullptr;
    [[maybe_unused]] DWORD result = FormatMessageW(
      fmtflags,
      nullptr,
      last_error,
      0,
      (LPWSTR) &msg,
      0,
      nullptr);
     
    assert(result != 0);
     
    std::fwprintf(stderr, L"error: %s", msg);
  }
}
Last edited on
Well, I am not actually making anything for windows. I am
making a 3ds cheat plugin. That code won't work.

I did, however, get
C:\\file.txt
to work. (on Windows)
Last edited on
Topic archived. No new replies allowed.