How to read data from a file in c and treat as a string?

Asked

Viewed 169 times

2

how to read data from a file in c and assign it to a string?

file. c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CONFIG "config.ini"

void main()
{
    char *data, *data1, *stream;
    FILE* arquivo;
    arquivo = fopen(CONFIG, "r");

    /*

    // data = fgets(stream, sizeof(arquivo), arquivo);
    // data1 = fscanf(arquivo, "%s", stream);

    */

    // printf("%s\t%s\n", data, data1);
    fclose(arquivo);
    // fopen(CONFIG, "w");
    return;
}

config.ini

Lorem ipsum auctor curabitur at justo maecenas hendrerit feugiat, adipiscing augue
accumsan ornareeu nunc iaculis cubilia, sodales quisque bibendum dapibus ullamcorper
ornare diam. consectetur pretium eros velit ante pellentesque taciti ullamcorper interdum
gravida himenaeos viverra mauris luctus hendrerit habitasse arcu fringilla, praesent
habitant mi facilisis curae fames quam sapien.

2 answers

4


To be able to read everything you need to know first how many bytes the file has.

What you need to do is:

  • Position yourself at the end with fseek and flag SEEK_END
  • Find out what byte it’s in ftell
  • Read this amount with bytes with fread from the beginning

Example:

void main()
{
    char *data, *data1, *stream;
    FILE* arquivo;
    arquivo = fopen(CONFIG, "r");

    fseek (arquivo, 0, SEEK_END); //posicionar-se no fim
    long dimensao = ftell (arquivo); //descobrir a dimensão
    fseek (arquivo, 0, SEEK_SET); //voltar ao inicio
    data = (char*) malloc ((dimensao+1) * sizeof(char) ); //alocar espaço para ler tudo

    if(data){ //se conseguiu alocar
        fread (data, 1, dimensao, arquivo); //ler tudo
        data[dimensao] = '\0'; //colocar o terminador
    }

    fclose(arquivo);

    return 0;
}
  • Thank you again Isac

  • The string contained in the pointer data is not well formed because it does not have the terminator \0 and malloc() does not allocate an extra byte for inclusion of that terminator.

  • @Lacobus Well put, it was something I missed. Thank you for warning me

  • I didn’t know that ftell. Always learning new things by reading your answers

  • @Jeffersonquesado Which is very useful by the way, for cases like this.

3

You can use the functions fread() and realloc() within a loop.

Every iteration of the loop, fread() is responsible for reading a small block of the input file, while realloc() is responsible for managing the memory required to accommodate each read block.

Here is an example (tested) illustrating the idea:

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

#define BUF_MAX_TAM (128)

int carregar_arquivo( const char * arq, char ** str )
{
    unsigned char buf[ BUF_MAX_TAM ] = {0};
    int total = 0;
    int n = 0;
    char * p = NULL;
    FILE * pf = NULL;

    pf = fopen( arq, "r" );

    if(!pf)
        return -1;

    p = malloc( 1 );

    while( (n = fread( buf, 1, sizeof(buf), pf )) != 0 )
    {
         p = realloc( p, total + n + 1 );
         memcpy( p + total, buf, n );
         total += n;
    };

    p[ total ] = '\0';
    *str = p;

    fclose(pf);

    return total;
}


int main( int argc, char * argv[] )
{
    int tam = 0;
    char * p = NULL;

    tam = carregar_arquivo( argv[1], &p );

    printf("%s\n\n", p );

    printf("Bytes lidos: %d\n", tam );

    free(p);

    return 0;
}

Testing:

./teste config.ini
Lorem ipsum auctor curabitur at justo maecenas hendrerit feugiat, adipiscing augue
accumsan ornareeu nunc iaculis cubilia, sodales quisque bibendum dapibus ullamcorper
ornare diam. consectetur pretium eros velit ante pellentesque taciti ullamcorper interdum
gravida himenaeos viverra mauris luctus hendrerit habitasse arcu fringilla, praesent
habitant mi facilisis curae fames quam sapien.

Bytes lidos: 389

Browser other questions tagged

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