Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read and write to a text file in C++?

Tags:

Hey everyone, I have just started to learn C++ and I wanted to know how to read and write to a text file. I have seen many examples but they have all been hard to understand/follow and they have all varied. I was hoping that someone here could help. I am a total beginner so I need clear instructions. Here is an example of what i'm trying to do:

#include <iostream> #include <fstream> using namespace std; string usreq, usr, yn, usrenter; int start () {     cout << "Welcome..." int main () {     cout << "Is this your first time using TEST" << endl;     cin >> yn;     if (yn == "y")         {             ofstream iusrfile;             ofstream ousrfile;             iusrfile.open("usrfile.txt", "w");             iusrfile >> usr;             cout << iusrfile;             iusrfile.close();             cout << "Please type your Username. \n";             cin >> usrenter;             if (usrenter == usr)             {             start ();             }         }     else         {             cout << "THAT IS NOT A REGISTERED USERNAME.";         }      return 0;  } 
like image 576
Nate Avatar asked May 18 '11 22:05

Nate


People also ask

What is read & write in C programming?

A file can be opened in a read, write or an append mode. Getc and putc functions are used to read and write a single character. We can write to a file after creating its name, by using the function fprintf() and it must have the newline character at the end of the string text.

What is the syntax for writing a file in C?

Writing a Fileint fputs( const char *s, FILE *fp ); The function fputs() writes the string s to the output stream referenced by fp. It returns a non-negative value on success, otherwise EOF is returned in case of any error. You can use int fprintf(FILE *fp,const char *format, ...)


1 Answers

Header files needed:

#include <iostream> #include <fstream> 

declare input file stream:

ifstream in("in.txt"); 

declare output file stream:

ofstream out("out.txt"); 

if you want to use variable for a file name, instead of hardcoding it, use this:

string file_name = "my_file.txt"; ifstream in2(file_name.c_str()); 

reading from file into variables (assume file has 2 int variables in):

int num1,num2; in >> num1 >> num2; 

or, reading a line a time from file:

string line; while(getline(in,line)){ //do something with the line } 

write variables back to the file:

out << num1 << num2; 

close the files:

in.close(); out.close(); 
like image 53
Code_So1dier Avatar answered Sep 22 '22 15:09

Code_So1dier