I'm having a simple i/o with file problem. I have the name coming from a string but it just wont open at all. Incoming code:

string notename[] = {"NULL","empty"};
ifstream readnote;

readnote.open(notename[x].c_str(),ios::in|ios::out);
        if(!readnote)
        {
            cout << "Read Error";
        }

its prolly something small but i keep getting the error, can u see it?

Dani AI

Generated

This is a classic working-directory / open-mode problem — exactly what hit (file was in a different folder) and what was pointing toward when recommending an error message. Quick checklist and practical steps to avoid the same trap:

  • Verify the actual name and index: print x and notename[x] before opening so you’re sure you’re trying to open the file you think you are.
  • Check the current working directory and whether the file actually exists there. In modern C++ use std::filesystem to diagnose quickly:
#include <filesystem>
namespace fs = std::filesystem;

auto fname = notename[x];
std::cout << "CWD: " << fs::current_path() << " — Trying: " << fname << '\n';
if (!fs::exists(fname)) std::cerr << "File not found: " << fname << '\n';
  • Match stream type to intent: use std::ifstream for read-only, std::ofstream to create/write, and std::fstream for read+write. Opening with read+write flags will usually fail if the file does not already exist; use the proper flags if you want creation/truncation.
  • When running from an IDE or on mac/iOS, remember the process CWD may not be the project folder. For GUI apps/bundles, resources live inside the app bundle — they aren’t in the executable CWD.
  • For actionable error text, print the OS error (e.g., std::strerror(errno) or perror) so you get a clear reason rather than a generic “Read Error.”

These checks will find most causes: wrong folder, case/extension mismatch, wrong open mode, or permissions.

Recommended Answers

All 2 Replies

What's the value of x? Neither of the values in notename suggest a valid file name, and if they do, you'd need to verify that the file is in the current working folder. I'd suggest trying perror to get more information on why the file didn't open successfully:

if (!readnote)
{
    perror("Read Error");
}

You can find perror in stdio.h.

x = 1;
oh god i feel like such a idiot... forgot the folder place of the file...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.