I am reading a .txt file in C
, my doubt is how (or in what way) the information that I get from a could be stored .txt
in a type variable char
without knowing the exact size of said char
in the text file .
That is, if I have the following in the .txt
:
www.stackoverflow.com
It should reserve 22 bytes, 21
for the characters themselves and 1 more for the 0
end. That is, do the following:
char url[22];
But in the case of having .txt
a url
(since I am working with URLs in my file) I don't know the exact amount to reserve, for example:
www.urlaleatorio.com.ve
How could it allocate memory (if it can, I really don't know) depending on said "url" in this case?
- Code in language
C
:
int main( ) {
FILE * archivo = fopen( "url.txt", "r" );
if( archivo == NULL ) {
perror( "Error en la apertura del archivo" );
return 1;
}
char url[22];
while( 1 ) {
fscanf( archivo, "%s%s", url );
if( feof( archivo ) != 0 ) {
break;
}
printf( "%s %s\n", url );
}
fclose( archivo );
printf( "\nSe ha leido el archivo correctamente...\n" );
return 0;
}
Be able, you can. Although things get a bit complicated.
The logic is simple: as you get data, you check if you have reached the last one (using a special character:
0
or\n
, for example).If your buffer fills up, and that end-flag hasn't arrived , then you increase the buffer. You could reserve another one and copy ... or directly call
realloc( )
, which does just that (with certain optimizations).A small example: we are going to read from the standard input, and we are going to store it in a buffer , which we will be resizing on the fly . At the end of the program, that buffer will be printed .
We will stop reading data when we reach a TABULADOR, that will be our end mark:
Think that this process is not the fastest in the world (not even the example is optimized, I have tried to make it clear and useful rather than its efficiency). In your case, you say you receive from HTTP . This protocol can indicate the size of the element sent. You could take advantage of this to allocate your buffer all at once.