I'm trying to write a set of parameters of a structure into a file, and then read it in the program. The structure has a int
type variable and a string
type variable(this string is separated by space). I've successfully written and then read the integer part of the structure, but when i try to do the same for the string, the program crashes. I think it has something to do with my the fprintf
statement, and trying to read a string separated by space.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <locale.h> int main(void) { // creating a FILE variable FILE *fptr; // integer variable int i = 0; char n[50]; // character variable struct cliente { char nome[50]; int nif; }; struct cliente client[0]; // open the file in write mode fptr = fopen("student", "w"); if (fptr != NULL) { printf("File created successfully!\n"); } else { printf("Failed to create the file.\n"); // exit status for OS that an error occured return -1; } // get student detail printf("Enter student name: "); scanf(" %[^\t\n]c", client[1].nome); printf("Enter student ID: "); scanf("%d", &client[1].nif); // write data in file fprintf(fptr, "%d %s", client[1].nif, &client[1].nome); // close connection fclose(fptr); // open file for reading fptr = fopen("student", "r"); // display detail printf("\Ficheiro:\n"); fscanf(fptr, "%d %s", &i, n); printf("ID: %d\n", i); printf(" %s", n); // close connection fclose(fptr); return 0;
}
https://stackoverflow.com/questions/65402349/cannot-write-read-string-separated-by-coma-into-a-file December 22, 2020 at 09:59AM
没有评论:
发表评论