Copy from txt file to other

Asked

Viewed 4,160 times

6

int main(void) {
    void copiaConteudo(FILE *arquivo, FILE *arquivo1);
    FILE *arquivo = fopen("tmp/exercicio.txt","r");
    if (arquivo == NULL)
    {
        printf ("Não foi possível abrir o arquivo");
        return 1;
    }

    FILE *arquivo1 = fopen("home/novo.txt","w");    
    copiaConteudo(arquivo,arquivo1);        
    fclose(arquivo);
    fclose(arquivo1);
    return 0;
}

void copiaConteudo(FILE *arquivo, FILE *arquivo1)
{
    string teste;
    teste = "Teste";
    char ler[100];
    while(fgets(ler,100,arquivo) != NULL)

    if (ler.find("Teste"))
    {
        fputs("0/",arquivo);    
    }
    else
    {
        fputs(ler, arquivo1);
    }
}

I have this code, which my intention is to copy from the exercicio.txt file to the new.txt file, I can copy everything, but now I wanted to include a parameter for it not to copy the lines that contains "test".
Man if there at the end is my attempt that did not work, how can I do this?

  • It seems that you want to do something simple, but not to understand well the explanation, I was able to detail ?

  • The ideal is to read the file and search in memory. But it may be that the goal is another.

  • I want to copy everything in the exercicio.txt file to the new.txt file, but I want to create a parameter, for everything that starts with Test, not enter the fputs(read, archive1); which is the function that is copying the contents of the exercicio.txt file

  • You have to decide which language wants to explain the problem. C is different from C++

4 answers

4

Well, how did you label the question with C++ and it really looks like you’re using the C++ for some high-level functions (string::find() for example), I will give an answer using only the C++.

Commenting a little on the function string:find, if it finds the value requested, it returns the position in which it starts at string, otherwise returns the value std::string::npos

Below is a functional program that eliminates any line that has the word 'test''

#include <fstream>
#include <string>

int main()
{
    auto input = std::ifstream("exercicio.txt");
    auto output = std::ofstream("novo.txt");

    std::string msg;
    while (std::getline(input, msg))
    {
        if ( msg.find("teste") != std::string::npos )
            continue;
        output << msg << std::endl;
    }
}

4

Here is a solution (tested) in language C capable of performing a buffered binary copy of two files:

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>


int main( int argc, char * argv[] )
{
    FILE * src = NULL;
    FILE * dst = NULL;
    size_t n = 0;
    size_t m = 0;
    unsigned char buf[ 1024 * 8 ];


    /* Verifica sintaxe */
    if( argc != 3 )
    {
        printf("Erro de sintaxe: %s ARQUIVO_ORIGEM ARQUIVO_DESTINO\n", argv[0] );
        return EXIT_FAILURE;
    }

    /* Abre arquivo de origem para leitura  */
    src = fopen( argv[1], "rb" );

    if(!src)
    {
        printf("Erro abrindo arquivo de origem para leitura: %s [%s]\n", argv[1], strerror(errno) );
        return EXIT_FAILURE;
    }


    /* Abre arquivo de destino para gravacao */
    dst = fopen( argv[2], "wb" );

    if(!dst)
    {
        fclose(src);
        printf("Erro abrindo arquivo de destino para escrita: %s [%s]\n", argv[2], strerror(errno) );
        return EXIT_FAILURE;
    }

    /* Efetua a copia dos arquivos */
    do {
        m = 0;

        n = fread( buf, 1, sizeof(buf), src );

        if( n > 0 )
            m = fwrite( buf, 1, n, dst );

    } while( (n > 0) && (n == m) );

    /* Verifica se houve erro durante a copia */
    if( m )
    {
        printf("Erro copiando arquivo: %s\n", strerror(errno) );

        fclose(dst);
        fclose(src);

        remove(argv[2]); /* Remove arquivo parcialmente copiado */

        return EXIT_FAILURE;
    }

    /* Finaliza com sucesso */

    fclose(dst);
    fclose(src);

    return EXIT_SUCCESS;
}
  • Thanks friend, but copy me already with you, my question is to have a condition not to copy for example the words that contain "TEST", I’m not able to find a way to include this, I’m reading all day on the C++ site about string::find, but I can’t apply to archive usage

2

If it is valid to use a command line (like the ones on linux, mac, even in windows) the concept of filter can be interesting. A filter accepts a textual input and returns an output also textual -- which allows strings, and can be used as a tool applicable to to various input files.

Via the command line we can use filters created by us or existing on operating system in question.

Hypothesis 1: Default filter grep (linux, mac or windows with gnu Utilitarios installed)

 grep -v 'teste' < exercicio.txt > novo.txt

grep -v -- lets pass only lines that do not contain the regular expression correspontende to the first parameter

Hypothesis 2: user-created filter (based on @Amadeus solution (+1))

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

int main(int argc, char* argv[]){
   string msg;
   if (argc == 2 ){
      while (getline(cin,msg)) {
         if ( msg.find(argv[1]) == string::npos )
            cout << msg << endl;
      }
   }
}

This filter is receiving the rejection pattern by argument. Usage:

g++ -o filtro filtro.cpp
filtro teste < exercicio.txt > novo.txt

1

I couldn’t understand Std::find very well, but I will use your examples to train, thank you very much for the answers!

I ended up solving it this way:

int main(void) {
  void copiaConteudo(FILE *arquivo, FILE *arquivo1);
  FILE *arquivo = fopen("tmp/exercicio.txt","r");
if (arquivo == NULL)
{
    printf ("Não foi possível abrir o arquivo");
    return 1;
}

FILE *arquivo1 = fopen("home/novo.txt","w");

copiaConteudo(arquivo,arquivo1);

fclose(arquivo);
fclose(arquivo1);
return 0;
}

void copiaConteudo(FILE *arquivo, FILE *arquivo1)
{

  char ler[100];
  char lu[20];
  while(fgets(ler,100,arquivo) != NULL)
{
        if (strcmp(ler,"Teste") < 0)
        {
            fputs(ler, arquivo1);
        }
}
  • 1

    I made another Edit, I’m still crawling on Stackoverflow :D

Browser other questions tagged

You are not signed in. Login or sign up in order to post.