Answers for "file handling c++"

C++
13

read a file c++

// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      //use line here
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
Posted by: Guest on July-07-2020
17

c++ files

// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}
Posted by: Guest on November-09-2019
7

how to read and write in a file c++

#include <iostream>
#include <fstream>
using namespace std;

ifstream file_variable; //ifstream is for input from plain text files
file_variable.open("input.txt"); //open input.txt

file_variable.close(); //close the file stream
/*
Manually closing a stream is only necessary
if you want to re-use the same stream variable for a different
file, or want to switch from input to output on the same file.
*/
_____________________________________________________
//You can also use cin if you have tables like so:
while (cin >> name >> value)// you can also use the file stream instead of this
{
 cout << name << value << endl;
}
_____________________________________________________
//ifstream file_variable; //ifstream is for input from plain text files
ofstream out_file;
out_file.open("output.txt");

out_file << "Write this scentence in the file" << endl;
Posted by: Guest on April-04-2020
1

file handling in c++

#include <iostream>
#include <fstream>
#include <cstring>
#include <process.h>
using namespace std;
int main()
{
    char name[999]; //Used to store data
    ofstream writeMode; //Created object of ofstream
    writeMode.open("name.dat"); //Opened the file in write mode
    cout<<"******** Writing into file ********"<<endl;
    cout<<"Enter your name: ";
    cin.getline(name, 999); //Accepts string with spaces and after spaces eg ____ ____
    writeMode<<name<<endl; //Putted data inside the file
    cout<<"Enter your age: ";
    cin>>name;
    cin.ignore(); //Wrote because number is accepted :P, may be
    writeMode<<name<<endl; //Again putted data inside the file
    writeMode.close(); //Closed the write mode
    ifstream readMode; //Created object of ifstream
    readMode.open("name.dat"); //Opened the file in read mode.
    cout<<"******** Reading into file ********"<<endl;
    readMode>>name;
    cout<<name<<endl; //Write the data to the screen
    readMode>>name; //again read the data from the file and display it
    cout<<name<<endl;
    readMode.close(); //Closed the read mode
    system("pause");
    return 0;
}
Posted by: Guest on August-18-2021

Browse Popular Code Answers by Language