954,492 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

Is it possible to open a user-defined file for output in C++?

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.

jrynik
Newbie Poster
2 posts since May 2009
Reputation Points: 10
Solved Threads: 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.

twomers
Posting Virtuoso
1,877 posts since May 2007
Reputation Points: 453
Solved Threads: 57
 

>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;
}
...
ArkM
Postaholic
2,001 posts since Jul 2008
Reputation Points: 1,234
Solved Threads: 348
 

Thank you both very much.

Thanks to you I've got a step further.

jrynik
Newbie Poster
2 posts since May 2009
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You