Hi,

I wish to delete the first 3 lines from a file. Following is my code which goes into an infifnte loop.

int main()
{
vector<string> text_file;
fstream fout;
int count = 1;

fout.open("tempfile.txt");
assert(!fout.fail());
string temp;
while(!fout.eof())
{
   if(count <= 3)
   {
     getline(fout,temp);
     count++;
   }

    if(count > 3)
    {
      getline(fout,temp);
      fout << temp << "\n";
    }
}
assert(!fout.fail());
fout.close();
/* End of writing to a file */
return 0;
}

Please help.

line 8: you might as well delete it because the compiler will delete it when you compile the program for release mode. Instead of using assert, just test as normal

if( !foud.is_open())
{
    // open failed
}

line 10: don't use eof() like that because it doesn't work that way. Here's the correction

while( getline(fout,temp) )
{
    // blabla
}

line 26: >> /* End of writing to a file */
You have done no such thing!

Ok so now you have read in the file into the linked list. Now you have to add code to rewrite the file.

Please use code tags. It is easier on my poor eyeballs.

There are issues involved with reading and writing to the same file. To do what you want to do, it is best to make a temporary file, then replace the original.

#include <iostream>
#include <fstream>

#include <cstdio>  // for tmpnam(), remove(), and rename()

using namespace std;

int main()
  {
  string filename = "tempfile.txt";
  string tempname = tmpnam( NULL );

  ifstream source;
  ofstream destination;
  string   line;

  try {
    if (!source.open( filename.c_str() ))
      throw string( "Could not open " ) +filename;

    if (!destination.open( tempname.c_str )
      throw string( "Could not open " ) +tempname;

    // Skip the first three lines
    for (int counter = 0; counter < 3; counter++)
      getline( source, line );

    // Copy the remainder
    while (getline( source, line )) destination << line;

    destination.close();
    source.close();

    // Replace the source file with the destination
    if (remove( filename.c_str() ) != 0)
      {
      remove( tempname.c_str() );
      throw string( "Could not overwrite to " ) +filename;
      }

    if (rename( tempname.c_str(), filename.c_str() ) != 0)
      throw string( "Could not rename " ) +tempname +" to " +filename;

    cout << "Success!\n";

  catch (string s) {
    destination.close();
    source.close();
    cerr << s << endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;
  }

Also, don't use ASSERT() for runtime errors. I personally believe that the macro is over-used, but whether anyone agrees or not it is still a Bad Thing to simply crash the program if something that can be expected to happen (even if we would prefer it didn't) goes wrong.

Hope this helps.

I made the change suggested. Following is the code. It is not able to delete the first three lines:

int main()
{
vector<string> text_file;
fstream fout;
int count = 1;

fout.open("tempfile.txt");
if(!fout.is_open())
{
  printf("Not open");
}
string temp;
while(getline(fout,temp))
{
  if(count <= 3)
  {
    count++;
  }
  if(count > 3)
  {
    fout << temp << "\n";
  }
}

fout.close();
/* End of writing to a file */
return 0;
}

I am not able to find what is wrong.

Thanks...

i also wish to delete the last three lines of a file.. should i use c++ program or a unix script.

if unix script i do not how to write it. please help

I made the change suggested. Following is the code. It is not able to delete the first three lines:
I am not able to find what is wrong.

That's because the file was opened for read, therefore writes will fail. You need to use two fstream objects. 1) ifstream to read from the original file, and 2) ofstream to write to a new temporary file. Here is some psudo code.

open input file 
open output file
for each row in the input file
    if counter > 3 then write to the output file
end of while loop
close both files
delete the original file (using remove() function)
rename the temp file to the same filename as the original (use rename() function)

i also wish to delete the last three lines of a file.. should i use c++ program or a unix script

what did your teacher tell you to do. write a c++ program or write a unix script?

this code is not a part of assignment. i am working on an independent project in which i wish to
delete the last three lines of a file iteratively. I tried this in unix shell scripting but it is not working..

lines=$(wc -l < s27.cnf)
target=$((lines-2))
sed '$target,$lines d' s27.cnf > f2.cnf
mv f2.cnf s27.cnf

I am getting an error "sed: 1: "$target,$lines d": undefined label 'arget,$lines d'
So was not sure what to use.

I would appreciate help on this.

Hi,

I am trying to delete the last 3 lines of file s27.cnf and write the output in new file s27_new.cnf. It is not working. What is wrong in this code.

int main()
{
   /* Initialize the variables */
   vector<string> lines;
   string temp;
   int cnt = 0;

   /* Input and output file defined */
   ifstream fin;
   ofstream fout;
   fin.open("s27.cnf");
   if(!fin.is_open())
  {
     printf("Not open");
  }
  
  while(getline(fin,temp))
  {
     lines.push_back(temp);
   }
   cnt = lines.size();
   cout << "#lines:" << lines.size() << '\n';

    fout.open("s27_new.cnf");
    for(int i=1; i<(cnt-2); i++)
   {
       getline(fin,temp);
       fout << temp;
       fout <<"\n";
    }

    fout.close();
    fin.close();

>>for(int i=1; i<(cnt-2); i++)
you don't need that cnt counter. Just delete it

lines 25-30 are reading the file again, not writing to it. Close fin before that loop

fin.close();
fout.open("filename");
for(int i = 0; i < lines.size()-2; i++)
   fout << lines[i] << "\n";
This article has been dead for over six months. Start a new discussion instead.