user8082931
user8082931

Reputation:

C- text files write details

I tried to do something simple to write some detail that I got from user to a txt file and it works but I want them to be at the same line and for some reason the last one that I write is in the next line.

printf("\nPassengers Details:\n===================\n");

printf("Please Enter Passenger`s Passport-->:");
scanf("%d", &p1.passportnum);
getchar();
printf("\nPlease Enter Passenger`s First NAME-->:");
fgets(p1.firstname, SIZE, stdin);
printf("\nPlease Enter Passenger`s Last NAME-->:");
fgets(p1.lastname, SIZE, stdin);

fpassengers = fopen("passengers.txt", "w");
fprintf(fpassengers,"%d %s %s", p1.passportnum, p1.firstname, p1.lastname);

fclose(fpassengers);

In the file it writes the first 2 at the same line and the last name in the next line .

How do I make them be at same line??

Upvotes: 0

Views: 110

Answers (1)

Overflow 404
Overflow 404

Reputation: 492

You have just to replace \n with \0in the last position of p1.firstname and p1.lastname. Here is a generic example:

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

#define SIZE 128

int main() {
    FILE* fpassengers;
    int passport_num;
    char first_name[SIZE];
    char last_name[SIZE];

    printf("\nPassengers Details:\n===================\n");
    printf("Please Enter Passenger`s Passport-->:");

    scanf("%d", &passport_num);
    getchar();

    printf("\nPlease Enter Passenger`s First NAME-->:");
    fgets(first_name, SIZE, stdin);
    first_name[strlen(first_name)-1] = '\0';

    printf("\nPlease Enter Passenger`s Last NAME-->:");
    fgets(last_name, SIZE, stdin);
    last_name[strlen(last_name)-1] = '\0';

    fpassengers = fopen("passengers.txt", "w");
    if (fpassengers == NULL) {
        perror("Fopen");
        exit(EXIT_FAILURE);
    }
    fprintf(fpassengers,"%d %s %s", passport_num, first_name, last_name);

    fclose(fpassengers);
}

You have also to check the return value of fopen.

Upvotes: 1

Related Questions