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



## Abhishek Dwivedi (Dec 7, 2008)

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 (Dec 7, 2008)

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:

```
#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.


----------



## Abhishek Dwivedi (Dec 7, 2008)

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 (Dec 7, 2008)

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:

```
$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.


----------



## Abhishek Dwivedi (Dec 7, 2008)

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  )


----------



## QwertyManiac (Dec 7, 2008)

Those should suffice! <string.h> (Or cstring) is the one that provides strcmp.


----------



## Abhishek Dwivedi (Dec 8, 2008)

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



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


----------



## QwertyManiac (Dec 9, 2008)

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


```
#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;
}
```


----------



## Abhishek Dwivedi (Dec 9, 2008)

hey guys,
what does this good() functions do??



> while (ip*.good()*)


----------



## QwertyManiac (Dec 9, 2008)

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:


```
while (ip)
```

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


----------



## Abhishek Dwivedi (Dec 25, 2008)

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 (Dec 25, 2008)

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:

```
/* 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.


----------



## Abhishek Dwivedi (Jan 1, 2009)

uh...1 more query 

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 (Jan 2, 2009)

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


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

A sample code, as always:

```
[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:

```
[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.


----------



## harryneopotter (Jan 2, 2009)

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.


----------



## Abhishek Dwivedi (Jan 2, 2009)

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

wht i was trying is this:



> char a[10],b[10], x[10];
> int pow, t;
> ifstream fout("test.dat");
> cin>>a>>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 (Jan 2, 2009)

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.


----------



## Abhishek Dwivedi (Jan 2, 2009)

yeah...i think i gota find the numbr of ch of the string n move the pointer pow-ch back to overwrite...


----------



## QwertyManiac (Jan 2, 2009)

Ack. WRONG.


```
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
```


----------



## Abhishek Dwivedi (Jan 2, 2009)

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


----------



## QwertyManiac (Jan 2, 2009)

But that won't do you any good, you can't overwrite. I don't see why you cant implement such a trivial thing, you just need to add an array to your existing code. No functions, nothing.


----------

