Open/read file without typing the extension name .txt

Feb 28, 2011 at 6:23am
Hi again! is there any way a program can read a .txt file without typing the .txt extension name? I need this for my ATM program for accessing an account number, it wouldn't look right if i have type 1234667.txt. I'm using Borland C++. Hope you can help me! Thanks!


#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <cstring.h>
#include <string.h>
#include <conio.h>

//using namespace std;

int main() {

char account[80];

//char string1[] = "jay";

char string2[] = ".txt";

char string3[17];

cout <<"Enter Account No.:";
cin >> account;

strcpy(string3, account);

strcat(string3, string2);


int bal = 0;
int x;
ifstream inFile;

inFile.open(account);
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}

while (inFile >> x) {
bal = bal + x;
}

inFile.close();
cout << bal << endl;
getch ();
return 0;
}
Feb 28, 2011 at 6:26am
closed account (4Gb4jE8b)
make another string or char array and have it copy the account string and then append += ".txt"
Feb 28, 2011 at 6:37am
can you please show me how to do that?
Feb 28, 2011 at 6:46am
closed account (4Gb4jE8b)
actually all you have to do is add this line strcat(account,string2); after the other strcat line

though i'm a little confused at what the purpose of string3 is. it would essentially be the same if you changed inFile.open(account) to inFile.open(string3). being that account is equal to string3 until the strcat line, which would then be equal after following the code mentioned in the previous paragraph.
Feb 28, 2011 at 6:51am
i got it working!

#include <iostream.h>
#include <iomanip.h>
#include <fstream.h>
#include <cstring.h>
#include <string.h>
#include <conio.h>

//using namespace std;

int main() {

char account[80];

char string1[] = ".txt";

char string2[17];

cout <<"Enter Account No.:";
cin >> account;

strcpy(string2, account);

strcat(string2, string1);




int bal = 0;
int x;
ifstream inFile;

inFile.open(string2);
if (!inFile) {
cout << "Unable to open file";
exit(1); // terminate with error
}

while (inFile >> x) {
bal = bal + x;
}

inFile.close();
clrscr();
cout << bal << endl;
getch ();
return 0;
}
Feb 28, 2011 at 6:57am
closed account (4Gb4jE8b)
yep. it's effectively the same thing i mentioned above
Topic archived. No new replies allowed.