Several C++ File Handling Queries**Urgent**

Status
Not open for further replies.

Abhishek Dwivedi

TechFreakiez.com
hi guys,
Am trying to make a program in C++(turboC++) where a user fills a form and all his details are saved in a file. This file is later used for Login and other purpose. Its something similar to banking.
Queries:
1) How to make the file name as variable?
The user gives a USERNAME in the form and file is made with that username. The input of username is taken in a char type array.
2) How to find a specific string in a file and tally it with a char type array?
A mother file is created with username & login code. When a user enters his username & code, they are checked via the mother file and if correct, he is taken to user menu. Input is taken in a char type array.
Thats all for now but i'll have more. Please reply ASAP. Thanks a lot :)
PS: how different is relo from TurboC++? Can i use it as a substitute? Any suggestions?
 

QwertyManiac

Commander in Chief
1. Just use the same char[] you recd as input in the file open argument.
2. Read the file line by line and use string.compare/strcmp functions to check against user input.

Here's a demo program in case you'd like to learn by reading code:
PHP:
#include <iostream>
#include <fstream>

using namespace std;

char filename[] = "login.txt";

int checkCred() {
    char *user, *pass;
    string line;
    ifstream ip(filename);
    cout << "Enter Username: ";
    cin >> (user = new char);
    cout << "Enter Password: ";
    cin >> (pass = new char);
    string usern(user), passw(pass);
    string full = usern + " " + passw;
    // Check against Mother File
    while ( ip.good() ) {
        getline(ip, line);
        if ( full.compare(line) ) {
            cout << "Correct." << endl;
            return 0;
        }
    }
    ip.close();
    cout << "Incorrect." << endl;
    return -1;
}

int newCred() {
    char *user, *pass;
    string line;
    cout << "Enter Username: ";
    cin >> (user = new char);
    cout << "Enter Password: ";
    cin >> (pass = new char);
    string usern(user), passw(pass);
    string full = usern + " " + passw + "\n";
    // W to User File
    ofstream us(user, ios::out);
    us << full;
    us.close();
    // W to Mother File
    ofstream mo(filename, ios::out|ios::app);
    mo << full;
    mo.close();
    cout << "User created." << endl;
    return 0;
}

int main(int argc, char **argv) {
    int choice(0);
    while ( 1 ) {
        cout << "1. Login" << endl << "2. New User" << endl << "3. Exit" << endl;
        cout << "Enter choice: ";
        cin >> choice;
        switch (choice) {
            case 1:
                checkCred();
                break;
            case 2:
                newCred();
                break;
            case 3:
                return 0;
            default:
                cout << "Enter the correct option..." << endl;
        }
        cout << endl;
    }
}

3. Relo is just an editor, it can use the new Borland compilers. Read Zeeshan's thread in the same section for details on how-to.
 
OP
Abhishek Dwivedi

Abhishek Dwivedi

TechFreakiez.com
hey QwertyManiac...thx a lot pal.
am using this to get the file name as a variable, chk if its correct:
user_file.open(c:\\program\\users\\username.c_str())
here username is the char array...
also, can u tell me more about using the string.compare/strcmp function while reading a file...the code u gave is not wht am looking for..i need a single function just to find the specific string frm a file so that i can use it again n again...
 

QwertyManiac

Commander in Chief
You will have to read the file line by line and also write to it the same way. Or instead of newline you can use a comma, or any other delimiter. For every item, check it against the username and password combo.

For example, once you get the new user ID/Pass, write it into the file as:
PHP:
$User<space>$Pass<delimiter>
Then while reading (Login), read up to a delimiter, and check with the ID/Pass got. In case its a string variable, use the str1.compare(str2) method. In case its a char[] variable, use strcmp(str1,str2) to check if they match.

Make this into a function for reuse.
 
OP
Abhishek Dwivedi

Abhishek Dwivedi

TechFreakiez.com
bingo...thx...i'll try it out n let u knw if it wrks...(the project is related to ma boards practice n so am limited to only a handful of header n lib file :( )
 
OP
Abhishek Dwivedi

Abhishek Dwivedi

TechFreakiez.com
hey guys, chk this code below...i've taken the input of username n password and combined them as a string, so the shud b like this:

abcd+pass bedf+pass ... ... ...


void login()
{
clrscr();
gotoxy(10,1);
cout<<"Please provide the Login details:";
char *user_l, *pass_l;
cout << "Enter Username: ";
cin >> (user_l = new char);
cout << "Enter Password: ";
cin >> (pass_l = new char);
string user_lc(user), pass_lc(pass);
string full_lc=user_lc+"+"+pass_lc;
cout<<"Checking our Database for your Login...";
delay(350);
}

now chk this code...here i wht i want is to read frm a file and store it in a STRING untill a space is encountered....as soon as the space is encountered, the STRING should b chkd against the user+pass combination and if incorrect, it should continue...can ne1 help me with this loop??

void login_check()
{
clrscr();
fstream check_user(c:\\system\\motherfile.pp, ios::in);
string buffer;
getline(check_user,buffer);
full_lc.compare(buffer);
//incomplete
 

QwertyManiac

Commander in Chief
Simply use the >> operator over the input file stream object. It reads up to a space or a newline anyway.

PHP:
#include <iostream>
#include <fstream>

using namespace std;

int main(int argc, char **argv) {
    ifstream ip("file.txt");
    // file.txt contains:
    // "abc+def ghi+jkl"
    string test("ghi+jkl");
    char *a;
    while (ip.good()) {
        ip >> (a = new char); // Reads till space, so: abc+def, ghi+jkl are the two reads.
        if (test.compare(a)) {
            cout << "Passed." << endl;
            return 0;
        }
    }
    cout << "Failed." << endl;
}
 

QwertyManiac

Commander in Chief
It just checks if the file is still good to read, its a combination of various checks (EOF, bad file, etc). You can simply use an EOF check or let it be implicit like this:

PHP:
while (ip)

Using .good() is just a good practice, nothing else.
 
OP
Abhishek Dwivedi

Abhishek Dwivedi

TechFreakiez.com
am trying to use "string" data type in Turbo C++ 3.0 but the data type is missing...
i've tried using <string> with "std::" instead of <string.h> but no luck...
guys plz help...

also, ne idea on how to add 2 char array...??
am trying to use this code in turbo c++...

string full_m=user_m + "+" + pass_m + "\n";
 

QwertyManiac

Commander in Chief
The string class is not present in Turbo C++ v3.0. (Try defining one of your own, that you could reuse.)

Use strcat to concatenate several strings.

From CPP.com:
Code:
/* strcat example */
#include <stdio.h>
#include <string.h>

int main ()
{
  char str[80];
  strcpy (str,"these ");
  strcat (str,"strings ");
  strcat (str,"are ");
  strcat (str,"concatenated.");
  puts (str);
  return 0;
}

This function is available in Turbo C++ v3.0 too, under the string.h include.
 
OP
Abhishek Dwivedi

Abhishek Dwivedi

TechFreakiez.com
uh...1 more query :D

i have a txt file in this format:

Abhi
Mike
Tim

Now i want to find a string in this file and replace it...

like a user wants "Mike" to be replaced with "Jack"...how do i do that?...i can search the string mike but thn how do i replace it???
 

QwertyManiac

Commander in Chief
That is quite simple. Just like how text editors would write the entire file back on modify+save, you need to do the same.

  1. Open file as ios::in.
  2. Read lines into array.
  3. Close file.
  4. Open same file as [noparse]ios::eek:ut.[/noparse]
  5. Iterate over the array and look for your value, and replace it (replace).
  6. Write each iterated line to file.
  7. Close file.

A sample code, as always:
Code:
[color=#BC7A00]#include <iostream>
#include <fstream>
#include <string>

#define BUFF 2048
[/color]
[color=#008000][b]using[/b][/color] [color=#008000][b]namespace[/b][/color] std;

[color=#B00040]int[/color] main ([color=#B00040]int[/color] argc, [color=#B00040]char[/color] [color=#666666]**[/color]argv) {

    ifstream a([color=#BA2121]"sample.txt"[/color]);
    string line;
    string b[BUFF];
    [color=#B00040]int[/color] i([color=#666666]0[/color]);
    [color=#008000][b]while[/b][/color] (getline(a, line).good()) {
        b[i[color=#666666]++[/color]][color=#666666]=[/color]line;
    }
    a.close();
    ofstream c([color=#BA2121]"sample.txt"[/color]);
    [color=#008000][b]for[/b][/color]([color=#B00040]int[/color] j[color=#666666]=[/color][color=#666666]0[/color]; j[color=#666666]<[/color]i; j[color=#666666]++[/color]) {
        [color=#008000][b]if[/b][/color] (b[j].find([color=#BA2121]"Mike"[/color])[color=#666666]!=[/color]string[color=#666666]::[/color]npos) [color=#408080][i]// Or any user str
[/i][/color]            b[j] [color=#666666]=[/color] [color=#BA2121]"Jack"[/color];
        c[color=#666666]<<[/color]b[j][color=#666666]<<[/color]endl;
    }
    [color=#008000][b]return[/b][/color] [color=#666666]0[/color];
}

You can also try string.replace() if its only a part of the string you wish to replace.

Which in our case would look like:
Code:
[color=#008000][b]if[/b][/color] (b[j].find([color=#BA2121]"Mike"[/color])[color=#666666]!=[/color]string[color=#666666]::[/color]npos) [color=#408080][i]// Or any user str
[/i][/color]    b[j].replace(b[j].find([color=#BA2121]"Mike"[/color]), string([color=#BA2121]"Jack"[/color]).length(), [color=#BA2121]"Jack"[/color]);

This will replace Mike with Jack in the string (say "Mike Eats" -> "Jack Eats") leaving the remaining parts intact.
 
hey dude ... for id and password thing u can try this :

make a structure containing the username and password variables.
like
Struct id{ char user [25], pass[25];
} accounts;



than to check the username use it :

fstream fib;
int h=0;
fib.open("Users.txt",ios::in|ios::ate);
while(!fib.eof())
{
off=((h)*sizeof(id));
fib.seekg(off,ios::beg) ;
fib.read((char*)&accounts,sizeof(id));
if(!strcmp(accounts.user,user)) //user being ur variable for user

// ur code
h++;
} //end of while loop



Hope it helps.
 
OP
Abhishek Dwivedi

Abhishek Dwivedi

TechFreakiez.com
@QwertyManiac...well the code is fine but its Turbo C++ and CBSE dsnt have some of the commands u used...thats y am stuck :p

wht i was trying is this:

char a[10],b[10], x[10];
int pow, t;
ifstream fout("test.dat");
cin>>a>>b;
ofstream ff("test.dat", ios::app);
while(fout.good())
{
fout>>x;
t=strcmp(a,x);
pow=fout.tellg();
if(t==0)
{
fout.seekg(pow);
ff<<b;
}
}

what am doing is that inputing 2 strings a & b...comparing a with data frm file (x) and storing its location in pow...thn if equal, going to that pow position and putting the string b....

the prblm is that b dsnt replaces but comes nxt to that line...
 

QwertyManiac

Commander in Chief
I've given the simple algorithm you would need to write back to the files, its above the code sample. You will need to write all the lines of the file again, along with the replaced string.

Of course your code would write it as a normal line, and not overwrite, cause its appending at the current file pointer location. There is no overwriting function for file operations.
 

QwertyManiac

Commander in Chief
Ack. WRONG.

Code:
OPEN FILE AS READ MODE.

LOOP TILL EOF
    GET A VALUE FROM THE FILE (OR A LINE, AS YOU PLEASE).
    >>  IF CURRENT CONTENT MATCHES THE COMPARE, REPLACE IT. <<
    STORE CONTENT OF THIS READ OPERATION IN AN ARRAY.
END LOOP

OPEN SAME FILE AS WRITE MODE (ERASES ALL CONTENT)

LOOP TILL END OF ARRAY
    STORE EACH VALUE OF ARRAY BACK TO THIS NEW FILE.
END LOOP
 
OP
Abhishek Dwivedi

Abhishek Dwivedi

TechFreakiez.com
ur 200% correct harsh but its a school project for boards so u basically have to scramble up every single command that u find in the book onto this code...lolz
thats y am sticking with seekp n tellg algo
 
Status
Not open for further replies.
Top Bottom