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:");
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.

Recommended Answers

All 3 Replies

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.

>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)) {
    if (!file) {
        std::cerr << "Can\'t open " << filename << std::endl;
        return 2;
} else {
    std::cerr << "Can\'t get filename" << std::endl;
    return 1;

Thank you both very much.

Thanks to you I've got a step further.

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.