Reading from a file

Asked

Viewed 42 times

0

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

At this time I have the following function (at this time just read and print 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:

inserir a descrição da imagem aqui

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

So I have two questions to ask:

1.Why does this happen?

2.What are the possible solutions?

Contents of the file: e106265f-bc8a-483c-b25d-f1f5ef1ec7b7 GUA

  • But why are you using sys calls instead of traditional file reading functions??

  • My teacher encourages students to use sys calls due to the subject of the chair.

1 answer

0


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

char* buff  = malloc(size);
  • It worked, thank you.

Browser other questions tagged

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