Delete line from a C file

Asked

Viewed 5,279 times

3

I’m doing a grocery project. Products are stored in a row-to-row file like this: codigo(int)$name(string)$quantity(int)$price(int)$. How can I delete a product( ie a specific line)?

1 answer

3

Very interesting question! One can do the following:

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

#define ARQUIVO_ESCOLHIDO 1
#define LINHA_DO_ARQUIVO 2

int main(int argc, char *argv[]){
    FILE *input = fopen(argv[ARQUIVO_ESCOLHIDO], "r"); //Arquivo de entrada.
    FILE *output = fopen("transferindo.txt", "w"); //Arquivo de saída.
    char texto[1001] = ""; //Uma string larga o suficiente para extrair o texto total de cada linha.
    unsigned int linha_selecionada = atoi(argv[LINHA_DO_ARQUIVO]);
    unsigned int linha_atual = 1;
    while(fgets(texto, 1001, input) != NULL){
        if(linha_atual != linha_selecionada){
            fputs(texto, output);
        }
        memset(texto, 0, sizeof(char) * 1001);
        linha_atual += 1;
    }
    fclose(input);
    fclose(output);
    remove(argv[ARQUIVO_ESCOLHIDO]);
    rename("transferindo.txt", argv[ARQUIVO_ESCOLHIDO]);
    return 0;
}

Basically, we create two pointers for files, one input and one output. The input loaded the file chosen by the user, which is the first parameter he passed on the command line. The output created its own file, transferindo.txt, who will simply receive the data we want to continue on our list.

Then we create a text string in the stack (remembering that it needs to be large enough to receive data for a text line in the file), and create two positive integers, one that converts the ASCII text of the second parameter of the command line into an integer that represents the line we want to remove, and the other that contains the line we are currently analyzing.

In the while loop, we use fgets to obtain the contents of each line, until fgets return NULL, that is, until it finds the end of the file. Here comes the interesting part: If the line whose deletion was requested on the command line is the line we are currently analyzing, we do nothing. Otherwise, we copy the line contents to our output file. Then, we clean the string in which we store the line and increase linha_atual in 1, which means we move to the next line of text of the input file.

After the while loop, we close the two pointers to files. Then we use the function remove to delete the file that the user requested to be modified, so that we can exchange it for the updated version of the file, transferindo.txt. So we use rename to rename the file transferindo.txt, giving him the original file name.

Ready! Now we have an updated file!

Remembering that you are not limited to function main. This example is just one of the many ways to implement what you want! :)

Browser other questions tagged

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