Binary files in C language

0

I have a question of how to store in a variable of type char a name among several saved in a binary file in C language, besides that the name is selected in a random way, to then show the name saved by means of the variable

this is the code:

#include<stdio.h>
#include<stdlib.h>
#include<time.h>

int main(){

    int cont=0,num;

    srand(time(NULL));
    char aux[50];

    FILE *archivo;
    num=rand()%51;
    archivo=fopen("doc.dat","rb");

    if(archivo==NULL){
        printf("Error de apertura");
    }

    while(!feof(archivo)){
        cont++;
        if(cont==num){
            fgets(aux,50,archivo);
        }
    }
    fclose(archivo);

    printf("%s",aux);
} 

and the binary file has the following saved:

Son GokuVegetaSon GohanSon GotenTrunksKrilinFreezerYamchaTen Shin HanGoku BlackBob EsponjaCalamardoDon CangrejoPatricio EstrellaYugi MutoAangZukoETAlfDanny PhantomBruce WayneDick GraysonJason ToddTim DrakeDrake ParkerJosh NicholsClark KentCrash BandicootSonic El ErizoShadow El ErizoJason VoorheesPamela VoorheesFreddy KruegerHomero J SimpsonBart SimpsonLisa SimpsonMoe SzyslakBarney GomezDraculaVictor FrankensteinHombre LoboHarry PotterMarioLuigiPrincesa PeachToadBowserLinkPrincesa ZeldaGanondorf
    
asked by Jose Ivan Chavez 21.06.2018 в 07:25
source

1 answer

1

Your intention is to read the file word by word ... for this you can use fscanf , which works exactly like scanf but on files.

On the other hand, your reading loop is wrong because, if you notice, it will only do a reading when cont==num ... the rest of the time it will not move the pointer of the file, then always will read the first 50 characters of it.

Staying with the word number num is as simple as creating a loop that iterates in the range (0,num) and, in each iteration, read a word from the file ... when the program leaves the loop you will have aux the searched word.

Admás, keep in mind that since C99 (dating from 1999 ... 19 years ago) it is possible to declare the variables anywhere in the code:

for( int cont=0; !feof(archivo) && cont != num; ++cont )
{
  fscanf(archivo,"%s",aux);
}
    
answered by 21.06.2018 в 08:33