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

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.
    
asked by anonymous 27.09.2017 / 22:18

2 answers

3

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

What you need to do is:

  • Position at the end with fseek and flag SEEK_END
  • Find out which byte you are on ftell
  • Read this amount with bytes with fread from the start

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] = '
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] = '%pre%'; //colocar o terminador
    }

    fclose(arquivo);

    return 0;
}
'; //colocar o terminador } fclose(arquivo); return 0; }
    
27.09.2017 / 23:10
3

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

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

Here's 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 ] = '
./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
'; *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:

#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 ] = '
./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
'; *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; }
    
28.09.2017 / 01:01