Morganuz
Morganuz

Reputation: 55

Get characters from text file and store them in string

I'm fairly new to C and I'm trying to make a program where I take names and other information from a text file and then store it on a .dat file. Here is my code:

#include <stdio.h>
#define MAX 30

typedef struct 
{
    char nombre[MAX];
    char apellido[MAX];
    char pais[MAX];
    unsigned int puntaje;
} Treg;


void ArmaBinario (FILE *archb);
void BuscaArchivo(FILE *archb);

void main (){
    FILE *archb; 

    ArmaBinario(archb); 
    BuscaArchivo(archb); 
}

void ArmaBinario (FILE *archb){
    FILE *archt;
    Treg ranking;
    char car; 
    int i; 

    archt = fopen("datos_ej26.txt","rt");

    if (archt == NULL) {
        printf("Error al abrir el archivo: el archivo no existe.");
    }
    else{
        archb = fopen("ranking.dat","wb");
        car = fgetc(archt);
        while (!feof(archt)){
            i = 0;
            while (car != ' ') {
                ranking.nombre[i] = car;
                i++;
                car = fgetc(archt);
            }
            car = fgetc(archt); car = fgetc(archt);
            i = 0;
            while (car != ' ') {
                ranking.apellido[i] = car;
                i++;
                car = getc(archt);
            }

            car = fgetc(archt); car = fgetc(archt);
            i = 0; 
            while (car != ' ') {
                ranking.pais[i] = car;
                i++;
                car = fgetc(archt);
            }

            fscanf(archt,"%u \n",&ranking.puntaje);
            fwrite(&ranking,sizeof(Treg),1,archb); 
            car = fgetc(archt);
            
        }

    } 

    fclose(archt);
    fclose(archb); 
 }


The structure of the text file is like this

Name Surname Country Points

When I run the program and then look into the .dat file I get no name and last name, usually the last characters of the country and then just an integer. For example for

John Smith Inglaterra 290

I get

Name: 
Country: terra
Points: 1685027142 

I'm sure the problem is in the handling of the characters, but I'm not sure what the exact issue is.

Thanks!

Upvotes: 0

Views: 64

Answers (1)

Ptit Xav
Ptit Xav

Reputation: 3219

You have different issues :

  • you skip one character between each word
  • you do not initialize the Treg variable before using it at each beginning of new line
  • it is not very useful to pass FILE* variables to functions if not initialized before in main and also as file archb is closed in function, it can not be used as is after exiting function.

Upvotes: 1

Related Questions