LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   c++ check if file exists (https://www.linuxquestions.org/questions/programming-9/c-check-if-file-exists-157136/)

Genjix 03-13-2004 11:25 AM

c++ check if file exists
 
Are there any apis that check whether a file is existant from a string you pass in?

LAMP_User 03-13-2004 12:24 PM

just open the file for reading, if this succeeds, then the file exists, something like this:
Code:

FILE* fp = fopen(path, "r");
if (fp) {
    // file exists
    fclose(fp);
} else {
    // file doesn't exist
}


Mega Man X 03-13-2004 12:37 PM

A file? Like... to check if a file exists when you try to open or write to it? If so, try something like this:

Code:

#include<fstream>
#include<iostream>
using namespace std;

int main()
{
    char fileName[80];
    char buffer[255];
    cout << "Give file name: ";
    cin >> fileName;

    ifstream fin(fileName);
    if (fin)  // check to see if file exists
    {
        cout << "This file has:\n";
        char ch;
        while (fin.get(ch))
            cout << ch;
        cout << "\n End of file \n";
    }
    fin.close();

    cout << "Opening file" << fileName << " in append mode...\n";

    ofstream fout (fileName,ios::app);
    if (!fout)  // if you try to open the file for writing and it fails, then
    {
        cout << " Impossible to open " << fileName << "for writing...\n";
        return(1);
    }

    cout << "\n Enter text to the file: ";
    cin.ignore(1,'\n');
    cin.getline(buffer,255);
    fout << buffer << "\n";
    fout.close();

    // try to re-open the file read-only
    fin.open(fileName);
    if(!fin)    // if fails, then:
    {
        cout << "Error opening file " << fileName << " for reading...\n";
        return(1);
    }

    cout << "Now the file contains:\n";
    char ch;
    while (fin.get(ch))
        cout << ch;
    cout << "\n End of the file reached, closing program...\n";
    fin.close();

    return 0;
}

Note: I've no idea if it will compile... I've not tested it myself, I just wrote it now :). But you will get the idea...

Regards!

xviddivxoggmp3 03-15-2004 12:08 AM

i do not have the exact syntax in front of me, but if i remember correctly that the open file function in output stream will return a value of 1 or 0 if/ifnot successful. the syntax above works, but you can use the test in alot other situations.


All times are GMT -5. The time now is 03:57 AM.