(training/beginner) Problem with segfault in fread() and fwrite() in . txt!

Asked

Viewed 40 times

1

Whoops, you guys!
First I wanted to say that I am very beginner and self-taught. I started with CS50 and I’m on the walk, rs. Contextualizing the code: 1x a week I work at an organic fair and I need to constantly write down the products and the amount I take. However, I would like to create an R table with this so I can work and study with them, and for this I want to create a C automation that receives a file. txt with these two or three columns and returns me with another . txt that has " ; "between the values.

Exemplifying:

Input: mamão 2000 g 
Output: mamão ; 2000 ; g 

That’s all!

I used fread() with a *buffer char I created and allotted memory with malloc and fwrite() with another *buffer char I get the modified copy (in thesis) with what I want it to do in the file.

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


//função para descobrir o tamanho do arquivo
long int sizeOfFile (FILE *infile);

//vâm vê o que é isso aí ainda
void CriarTabela (char *text, char *modText);

//a ideia é ser nomeado o arquivo de entrada que deseja modificar e o nome em que o programa irá salvá-lo depois
int main (int argc, char *argv[])
{
    //avisa o usuário se o programa não for utilizado corretamente
    if (argc != 3)
    {
        fprintf(stderr, "./tabela_sc input.txt output.txt\n");
        return 1;
    }
    //gravando os nomes dos arquivos
    char *infile = argv[1];
    char *outfile = argv[2];
    
    //abrindo arquivos de texto e criando nova tabela
    FILE *raw_table = fopen(infile, "r");    
    FILE *mod_table = fopen(outfile, "w");

    //se não houver memória, encerrar programa
    if (raw_table == NULL || mod_table == NULL)
    {
        fprintf(stderr, "Não há memória suficiente para realizar a operação!\n");
        return 2;
    }

    //descobrindo tamanho do arquivo para inicar array
    long int sf = sizeOfFile(raw_table); 
    
    //criando buffer array para armazenar o arquivo
    char *origTable = malloc(sizeof(sf));
    //criando +1000 bytes de memória para modificações (arbitrário)
    char *modTable = malloc(sizeof(sf + 1000));
    
    fread(origTable, sizeof(char), sf, raw_table);

    CriarTabela (origTable, modTable);

    
    fwrite(modTable, sizeof(char), sizeof(char), mod_table);
    
       
    fclose(raw_table);
    fclose(mod_table);
    free(origTable);
    free(modTable);

    return 0;
    
}

long int sizeOfFile (FILE *infile)
{
    fseek(infile, 0, SEEK_END);
    long int sf = ftell(infile);

    return sf;
} 

void CriarTabela (char *text, char *modText)
{
    int modificacoes = 0;

    for (int i = 0; text[i] != EOF; i++)
    {
        if (i == 0)
        {
            modText[i + modificacoes] = origText[i];
        }
        // se for um espaço em branco seguido/precedido por um caractere e seguido/precedido por um número, insira "; " e atualize o número de modificações feitas 
        else if ((isblank(origText[i]) && isalpha(origText[i - 1]) && isdigit(origText[i + 1])) || 
                (isblank(origText[i]) && isdigit(origText[i - 1]) && isalpha(origText[i + 1])))
        {
            modText[i + modificacoes] = origText[i];
            modText[i + 1 + modificacoes++] = ';';
            modText[i + 1 + modificacoes++] = ' ';
        }
        
        else
        {
            modText[i + modificacoes ] = origText[i];
            //teste
            printf("%c", origText[i]);
        }
    } 
}

When it didn’t work out, I thought it was a problem with the somewhat gambiarristic logic I had used to make these modifications in Criatabela(), but it seems that the problem lies in the original *buffer char. So I inserted a printf in the function Create table() to see what happened and lo and behold this seg fault.

Does anyone have any idea what I’m doing wrong?

segfault

  • Here: malloc(sizeof(sf)); you are allocating the size of a long and not the amount of bytes indicated by sf. As, from what I understand, your input file can contain lines of different lengths will be that it would no longer be practical to use fgets/fputs and handle the changes line by line?

No answers

Browser other questions tagged

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