Delete row of a file in C

3

I'm doing a project for a grocery store. The products are stored in a file line by line like this: code (int) $ name (string) $ quantity (int) $ price (int) $. How can I delete a product (ie, a specific line)?

    
asked by anonymous 24.04.2017 / 19:10

1 answer

3

Very interesting question! You 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 created 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 a file of its own, transferindo.txt , which will simply receive the data we want to remain on our list.

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

In the while loop, we use fgets to get the contents of each line, until fgets returns NULL, that is, until it finds the end of the file. Here's the interesting part: If the line whose exclusion was requested from the command line is the line we're currently analyzing, we do nothing. Otherwise, we copy the contents of the line to our output file. Then we clear the string in which we store the line and increase linha_atual by 1, which means we move to the next line of text in the input file.

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

Ready! Now we have an updated file!

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

    
24.04.2017 / 20:23