Storing a string in a file in C

I created a small program for entering some records into a file.

#include<stdio.h> int main(void) { FILE *fp; //opening a file to write fp = fopen("try.rec","w"); if(fp == NULL) { printf("\nSorry! Couldn't Create File"); exit(-1); } int id = 1; char name[300] = "Cipher", address[300] = "Virtual Street", phone[20] = "223322212"; fprintf(fp,"%d, %s, %s, %s", id, name, address, phone); fclose(fp); return 0; } 

Now he is doing a good job, and there is no mistake. But I also made a small program to read this entry:

 #include<stdio.h> int main(void) { FILE *fp; fp = fopen("try.rec","r"); if (fp == NULL) { printf("Could not Access File. :("); return -1; } int id; char name[300], add[300], phone[20]; fscanf(fp, "%d , %s , %s , %s",&id, &name, &add, &phone); fclose(fp); printf("\nDetails from File try.rec\n---------------------------\nID: %d \nName: %s \nAddress: %s \nPhone: %s \n", id, name, add, phone); return 0; } 

But when printing the third line, it prints garbage values. I went deeper and found out that when I replace "Cipher" with "Cipher " (with one extra space) in my first program and run it, then the third line in the second program displays only Virtual (and nothing after the space), and then the fourth string is garbage again.

So, are there any other good alternative ways to put and get a line from a file in C. Or am I doing the wrong thing in any of my programs?

Foreboding for your help!

Thanks at Advance.

+4
source share
2 answers

The problem is that the %s format tells fscanf to read all characters without spaces, so

 fscanf(fp, "%d , %s , %s , %s",&id, &name, &add, &phone); 

will read "Cipher," in name (aside: the correct argument would be name instead of &name ), then the next conversion will fail because fscanf does not find a ',' .

With a space after "Cipher " scan stops after the space is found, and then the next scan stops between "Virtual" and "Street" , and then there is no ',' as the format is required and no further conversions are performed.

You should check the return value of fscanf to make sure that the appropriate number of conversions has been performed, and handle the situation accordingly if there are too few successful ones.

Here you can use the character set format tha %[^,] to scan in your lines,

 fscanf(fp, " %d , %[^,] , %[^,] , %s", &id, name, add, phone); 
+6
source

Check the return value of fscanf , it returns the number of successful conversions. In addition, you specify fscanf functions to separate tokens in spaces (spaces in the format string), so a string containing spaces (for example, "Virtual Street" ) is considered two tokens.

I recommend that you read the entire line using fgets , and then use strtok to separate the line from commas.

+1
source

Source: https://habr.com/ru/post/1447732/


All Articles