Reading a file

0

I'm trying to read the contents of a file to a string, then use that same string in some operations.

At this moment I have the following function (at this moment only reads and prints the content):

char* ler_ficheiro(char* file_name){
int iSource,n;
char *buff;
char *buffer_retorno;

iSource = open(file_name, O_RDONLY);

if(iSource == -1){
    close(iSource);
    exit(1);
}

while(n = read(iSource, buff,1) > 0){
    printf("%s",buff);
}
return buffer_retorno;
}

My problem is that when I run the program I get the following result:

Some of these characters are part of the contents of the file, but not all of them.

I have two questions to ask:

1. Why does this happen?

2. What are the possible solutions?

File Content: e106265f-bc8a-483c-b25d-f1f5ef1ec7b7 GUA

    
asked by anonymous 05.01.2019 / 20:02

1 answer

0

The problem is that the read function does not allocate memory to the buffer. This means that you first have to initialize the buff pointer with a valid address. Ex:

char* buff  = malloc(size);
    
05.01.2019 / 21:33