Reverse file content without using an array in C ++
2 answers
Since you would not like to use arrays, vectors or anything like that, you can work it out.
Note: using temporary storage will make it more compact.
The idea is to use three functions:
1- get_line_num: Counts the line numbers of the file.
2- goto_line: Places the read cursor on a specific line.
3- reset: place the read cursor at the beginning of the file.
There is a lot of I / O in the program, which is not good, but since you don't want to use extended structs, it might help.
algorithm:
- open source file.
- open temp file.
- loop from last line to first line
- read a line from the input file.
- add line to temp output file
- end of cycle.
- delete the old source file.
- rename the temp file the same as the original file.
Headers:
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int get_line_num(ifstream& myfile);
ifstream& goto_line(ifstream& myfile, int line_num);
void reset(ifstream& myfile);
int main()
{
ifstream in;
ofstream out;
string line;
char* original = "original file name";
char* dest = "temp file name";
in.open(original);
out.open(dest, ios::app);
int num_of_lines = get_line_num(in);
for (int i = num_of_lines ; i ; --i)
{
goto_line(in, i);
getline(in, line);
reset (in);
out << line << "\n";
}
in.close();
out.close();
remove(original);
rename(dest, original);
cout <<"\n\n\n";
}
int get_line_num(ifstream& myfile)
{
int number_of_lines = 0;
string line;
while (getline(myfile, line))
++number_of_lines;
reset (myfile);
return number_of_lines;
}
ifstream& goto_line(ifstream& myfile, int line_num)
{
string s;
myfile.seekg(ios::beg);
for(int i = 1; i < line_num; ++i)
getline(myfile, s);
return myfile;
}
void reset(ifstream& myfile)
{
myfile.clear();
myfile.seekg(0, ios::beg);
}
0
source to share
- Create an output file.
- Read line from input using getline () api which returns char *
-
and. write it to the output file if it is the first line read.
b. Copy the content of the output file, write a line and add the copied content.
- Do this in a loop until a line is read in the input file.
EDIT : with some modifications, it should work for your case
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE * inputfp;
FILE * outputfp;
char * line = NULL;
size_t len = 0;
ssize_t read;
long fsize =0;
char* fstring;
inputfp = fopen("/etc/input", "r");
outputfp = fopen("etc/output", "r+");
if (inputfp == NULL || outputfp == NULL)
exit(EXIT_FAILURE);
while ((read = getline(&line, &len, inputfp)) != -1) {
fseek(outputfp, 0, SEEK_END);
fsize = ftell(f);
fseek(outputfp, 0, SEEK_SET);
fstring = malloc(fsize + 1);
fread(fstring, fsize, 1, f);
fstring[fsize] = 0;
fseek(outputfp, 0, SEEK_SET);
fputs(line, outputfp);
fputs(fstring, outputfp);
}
fclose(inputfp);
fclose(outputfp);
if (line)
free(line);
exit(EXIT_SUCCESS);
}
0
source to share