Cnoob
Cnoob

Reputation: 11

Write to txt file

I have a problem when trying to write to a txt file. I'm making a car register and after adding 2 cars to it, it looks like this in the txt file.

BMW
 Car
 ABCD1234
 Herald
 45
Fiat
 Car
 QWER1234
 RONALD
 20

My wish is to get it on the same line like this.

BMW Car ABCD1234 Herald 45
Fiat Car QWER1234 RONALD 20

This is my "save" and "add vehicle" function atm.

int save(vehicle_t * v, int count)
{
    FILE * f;
    f = fopen("reg.txt", "w");
    if(f == NULL)
    {
        printf("Could not open!\n");
        return 0;
    }
    else
    {
        int i;
        for(i=0; i < count; i++)
        {
            fprintf(f, "%s %s %s %s %d\n", v[i].brand, v[i].type, v[i].reg, v[i].owner.name, v[i].owner.age);
        }
    }
    fclose(f);
}
void add_vehicle(vehicle_t *v, int count)
{
    char brand[NSIZE]; char type[NSIZE]; char reg[NSIZE]; char name[NSIZE];
    int age;
    printf("Brand: ");
    fgets(brand, NSIZE, stdin);
    strcpy(v[count].brand, brand);
    
    printf("Type of vehicle: ");
    fgets(type, NSIZE, stdin);
    strcpy(v[count].type, type);
    
    printf("Reg number: ");
    fgets(reg, NSIZE, stdin);
    strcpy(v[count].reg, reg);

    printf("Owners name: ");
    fgets(name, NSIZE, stdin);
    strcpy(v[count].owner.name, name);

    printf("Owners age: ");
    v[count].owner.age = num_check(MAX_AGE, MIN_AGE);
}

My thought is that fgets adds \n at the end of an array, but how do I get rid of this problem when working with structs?

Upvotes: 1

Views: 100

Answers (2)

fgets returns all the characters on the line including the trailing \n. To keep fprintf from printing the \n characters you can change the fprintf call to

fprintf(f, "%*.*s %*.*s %*.*s %*.*s %d\n",
          strlen(v[i].brand)-1,      strlen(v[i].brand)-1,      v[i].brand,
          strlen(v[i].type)-1,       strlen(v[i].type)-1,       v[i].type,
          strlen(v[i].reg)-1,        strlen(v[i].reg)-1,        v[i].reg,
          strlen(v[i].owner.name)-1, strlen(v[i].owner.name)-1, v[i].owner.name,
          v[i].owner.age);

This instructs it to output all but the last character of each string.

Upvotes: 2

vmp
vmp

Reputation: 2420

You can put the terminator one position to the left with:

fgets(name, NSIZE, stdin);
name[strlen(name) - 1] = '\0';

or you could use scanf:

scanf("%100[^\n]%*c", name);
//but here I've put a maximum 100 chars inside the string, 
//not using the variable

There are other ways to do that with scanf but if you are a beginner I'd recommend you to stick with one of the two options above.

Upvotes: 1

Related Questions