input file

i had a question regarding input files. is there any way to set up a message to pop up if the input file doesn't exist? this is the code i have. they want me to have a code that works with the file but also want a prompt to come up if the file doesn't exist.

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
#include <iostream>
 #include <fstream>
 using namespace std;

 int main()
 {
 ifstream inFile;
 double value1, value2, value3, value4, value5, value6, value7, sum;

 inFile.open("weekly_sales.txt");
 cout << "reading data from the file" << endl;

 inFile >> value1;
 inFile >> value2;
 inFile >> value3;
 inFile >> value4;
 inFile >> value5;
 inFile >> value6;
 inFile >> value7;

 inFile.close();

cout << "Here are the weekly sales:\n"
 << value1 << " " << value2
 << " " << value3 << " "  << value4 << " " << value5
 << " " << value6 << " "  << value7<< endl;
 
 sum = value1 + value2 + value3 + value4 + value5 + value6 + value7;

 cout << "Their sum is: " << sum << endl;
 return 0;
}
Last edited on
You can't check if a file exists in C++. You can check if a file is open though which essentially might imply that it either exist or does not exist.

1
2
3
4
if(!file.is_open())
{
  // error! maybe the file doesn't exist.
}
Last edited on
the variable called between them might be causing the problem I am noob myself
Under Windows you can use this function.
1
2
3
4
5
6
7
8
9
10
11
12
13
bool FileExists (const char *fname)
{
  WIN32_FIND_DATAA FindFileData;

  HANDLE hFile = FindFirstFileA (fname, &FindFileData);

  if (hFile == INVALID_HANDLE_VALUE)
    return false;

  FindClose (hFile);

  return true;
}


Remember to include <Windows.h>
Topic archived. No new replies allowed.