0

Hello,

I am working on a program, part of which is opening a file.

As I expect the program to check if the (text) file contain certain data. That's why it would be useful if program users could enter the file to check.

I've tried to do it by combining writing the printf and fopen with r option, but the compiler returners error messages.
This is what I have 'created':
printf("Select the file to open:");
scanf("%d",&a);
fopen("%d", a , "r")

Can anyone tell me if it is possible to get my idea across to PC so that the program runs correctly?

Thanks for all replies.

3
Contributors
3
Replies
4
Views
8 Years
Discussion Span
Last Post by jrynik
0

Do it more like this:

char fileName[30];
printf( "Enter filename: " );
scanf( "%s", fileName );
FILE *pFile;
pFile = fopen( fileName, "r" );
... etc
fclose( fFile );

Though technically this is C++ so you should use fstreams, really.

0

>technically this is C++ so you should use fstreams, really
Moreover, you should use std::string instead this unsafe C-style input of a single word (see %s format specification) in 30-byte buffer (the right way to nowhere):

std::string filename;
std::ifstream file;
cout << "Enter filename: ";
if (getline(cin,filename)) {
    file.open(filename.c_str());
    if (!file) {
        std::cerr << "Can\'t open " << filename << std::endl;
        return 2;
    }
} else {
    std::cerr << "Can\'t get filename" << std::endl;
    return 1;
}
...
0

Thank you both very much.

Thanks to you I've got a step further.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.