Creating dynamic structures based on a text file

0

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

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

    
asked by anonymous 06.07.2016 / 01:36

2 answers

0

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

    
06.07.2016 / 07:21
0

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

If you want to get a file number, of course it would be easier if the file value were in binary. For the file would have a value of 4 spaces with values from 0 to 255 , responsible for storing an integer.

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

For this you should remember that these characters are represented by binary values of the Ascii table. If you were to read the file and get those values, you would have the values 52 and 51 , as these are the values representing the 4 and > 3 .

How to pass this to an integer variable?

You need to know the size of the value to be read. Assuming the file has the 4378 value, we read the file and store the value in a char num[4] , we must go through char backwards to calculate.

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
    
06.07.2016 / 21:23