Create dynamic structures based on a text file

Asked

Viewed 57 times

0

Is it possible to create a dynamic structure based on information stored in a text file(file)? Or this is only possible if the file is binary?

For example: if I have a number (5) in a text file, can I go find it and store it in a dynamic structure as an integer? Or that’s impossible because the text file data is all 'char'?

  • Text files can behave as if they were keyboard. Also the keyboard data is all char.

2 answers

0

Yes, it is possible. You read the file char to memory and then cast it normally. The file is basically another type of memory.

0

The characters in the files are the same as in the table Ascii, that is, it is a char with the value of 0 to 255, as well as the permitted values for a char in C.

In case you want to take a number of a file, of course it would be easier if the value of the file was in binary. Because in the file would have a value of 4 spaces with values of 0 to 255, responsible for storing a whole.

And if it is a number represented by the characters 43?

For this you should remember that these characters are represented by binary table values Ascii. If you were to read the file and take these values, you would have the values 52 and 51, because the values represent the characters 4 and 3.

How to pass this to an integer variable?

It is necessary q if you know the size of the value to be read. Assuming the file has the value 4378, we read the file and store the value in a char num[4], we must walk the char from front to back for calculation.

int number = 0; // deve-se iniciar o valor em 0
for(int x = 0; x<4; x++){
    number += pow(10,x)*num[3-x]; // a posição é sempre o tamanho do vetor - 1
}

printf("%d\n", number);
4378

Browser other questions tagged

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