I am writing a program using c++
, and in one part of that program I need to read a file and write it to another, the file is read and written, however the new file is not written completely.
I am working with the compiler g++
in Deepin 15.11
.
The code I'm using is the following:
#include <iostream>
#include <fstream>
int main(int argc, const char* argv[]){
//Obtenemos el argumento, la ruta del archivo la paso como argumento
std::string file_name = argv[1];
//El archivo de entrada que estoy usando es un archivo ".m4a",
//intento leerlo y escribirlo en otro archivo con la misma extención, sin embargo este se daña debido a que no se escribe completo.
std::ifstream input_file(file_name, std::ios::binary);
//Definimos una variable donde guardar los datos leídos
std::string line;
//Preparamos el archivo de salida, el cual también es ".m4a"
std::ofstream output_file("./archivo de salida.m4a", std::ios::binary);
//Verificamos si el archivo esta abierto
if(input_file.is_open()){
while(!input_file.eof()){
getline(input_file, line);
//Como prueba guardaremos los datos conforme se lean
output_file << line;
}
//Cerramos el archivo de entrada
input_file.close();
//Cerramos el archivo de salida
output_file.close();
}
return 0;
}
The output file has fewer lines than the original.
Why does this happen?
Thanks in advance.
The thing is, by definition, when
getline
reading a line it doesn't add the delimiter (in this case '\n', the newline character) to the output string. So when you write each "line" to the output file, it puts everything without separating it into lines.To fix it you would have to manually add the missing delimiter. I mean, you should change
by
I have to mention that this is not the correct way to read a binary file (like a song), because if
getline
it doesn't find a newline character in the file, it will load all the content in memory and if it is a big file it will a waste of memory.