I am new to C program and I am working on a program which is writing a set of struct to a .txt file.
This is my try:
#include <stdio.h>
struct FileSig {
char name[256];
char mode;
char user_id;
char group_id;
char size;
char time_last_mod[50];
};
int main(int argc, char **argv)
{
struct FileSig FileSig1;
FILE *fp_Out;
fp_Out = fopen( "out.txt" , "w" );
printf("Enter name: ");
scanf("%s", FileSig1.name);
fprintf(fp_Out, "Name: %s\n", FileSig1.name);
printf("Enter mode: ");
scanf("%s", FileSig1.mode);
fprintf(fp_Out, "Mode: %s\n", FileSig1.mode);
printf("Enter user id: ");
scanf("%s", FileSig1.user_id);
fprintf(fp_Out, "userID: %s\n", FileSig1.user_id);
printf("Enter group id: ");
scanf("%s", FileSig1.group_id);
fprintf(fp_Out, "groupID: %s\n", FileSig1.group_id);
printf("Enter size: ");
scanf("%s", FileSig1.size);
fprintf(fp_Out, "size: %s\n", FileSig1.size);
printf("Enter time last modifly: ");
scanf("%s", FileSig1.time_last_mod);
fprintf(fp_Out, "time_last_mod: %s\n", FileSig1.time_last_mod);
// fp_Out = fopen( "out.txt" , "w" );
// fprintf(fp_Out, "Name: %s\nMode: %d\nUserID:%d\nGroupID: %d\nSize:%d\nTime last modifly:%s", FileSig1.name, FileSig1.mode, FileSig1.user_id, FileSig1.group_id, FileSig1.size, FileSig1.time_last_mod);
fclose(fp_Out);
return 0;
}
When I run it after the second input it said Segmentation fault (core dumped).
More anyone please help me with this? I am new on this and I am like to learn.
The "%s" format specifier is for strings. But mode
is a character. Use "%c" for characters. Also, pass the address you want the character stored in to scanf
, not an uninitialized value.
"%s" is for strings, but mode
is of type char
, thus you should use "%c", like this:
scanf("%c", &FileSig1.mode);
fprintf(fp_Out, "Mode: %c\n", FileSig1.mode);
Notice how I took the address of mode
, since scanf()
takes a pointer as an argument.
PS: You need to change all your scanf and printf that read a character instead of a string to follow this advice.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.