How do I create a CSV in C by incrementing the first number?

1

I generated this csv:

1;0
2;0
2;0
2;0
2;1
2;2
2;2
2;2
2;2
2;3

...

How do I get the first number of each line to increment it?

And how can the first line not be skipped?

int gerarRelatorioHash(int colisoes) {
     FILE *pont_arq;

     pont_arq = fopen("relatorio.csv", "r+");

     if(pont_arq == NULL) {
        printf("Erro na abertura do arquivo!");
        return 1;
    }

    int qtd;
    fscanf(pont_arq, "%d", &qtd);
    qtd++;

    fseek(pont_arq, 0, SEEK_END);\
    fprintf(pont_arq, "\n%d;%d", qtd,colisoes);

    fclose(pont_arq);
    printf("Dados gravados com sucesso!\n");
    return 0;
}

The idea that qtd is a counter to which each line that it skips it makes a qtd++ and the second parameter is what was passed.

Example of how it should have been:

1;0
2;0
3;0
4;0
5;1
6;2
7;2
8;2
9;2
10;3
....
    
asked by anonymous 05.07.2018 / 02:04

1 answer

3

Instead of changing the input file, you can simply convert it by writing an output file with the new content, see:

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

#define LINHA_MAX_LEN  (256)

int main( int argc, char ** argv )
{
    int n = 0;
    int seq, val;
    char linha[ LINHA_MAX_LEN + 1 ];
    FILE * in = NULL;
    FILE * out = NULL;

    in = fopen( argv[1], "r");

    if(!in)
    {
        printf("Erro abrindo arquivo de entrada para leitura.\n");
        return 1;
    }

    out = fopen( argv[2], "w");

    if(!out)
    {
        printf("Erro abrindo arquivo de saida para gravacao.\n");
        fclose(in);
        return 1;
    }

    /* Para cada linha do arquivo de entrada */
    while( fgets( linha, sizeof(linha), in ) )
    {
        /* Incrementa contador de linhas */
        n++;

        /* Interpreta linha lida */
        sscanf( linha, "%d;%d\n", &seq, &val );

        /* Grava a linha com novo sequencial no arquivo de saida */
        fprintf( out, "%d;%d\n", n, val );
    }

    fclose(in);
    fclose(out);

    printf("Linhas Processadas: %d\n", n );

    return 0;
}

Testing:

$ ./enumerar relatorio.csv saida.csv
Linhas Processadas: 10

Entry ( relatorio.csv ):

1;0
2;0
2;0
2;0
2;1
2;2
2;2
2;2
2;2
2;3

Output (% with%):

1;0
2;0
3;0
4;0
5;1
6;2
7;2
8;2
9;2
10;3
    
05.07.2018 / 05:39