c - read a file line by line into structure -
code :-
#include <stdio.h> #include <string.h> int main () { file *fp; const char s[3] = " "; /* trying make 2 spaces delimiter */ char *token; char line[256]; fp = fopen ("input.txt","r"); fgets(line, sizeof(line), fp); token = strtok(line, s); /* walk through other tokens */ while( token != null ) { printf( " %s\n", token ); token = strtok(null, s); } return 0; }
input.txt below :
01 sun oct 25 16:03:04 2015 john nice meeting you! 02 sun oct 26 12:05:00 2015 sam how you? 03 sun oct 26 11:08:04 2015 pam ? 04 sun oct 27 13:03:04 2015 mike morning. 05 sun oct 29 15:03:07 2015 harry come here.
i want read file line line , store in variables like
int no = 01 char message_date[40] = sun oct 27 13:03:04 2015 char friend[20] = mike char message[120] = morning.
how achieve ? possible store file line line structure
struct { int no.; char date[40]; char frined[20]; char message[120]; };
with above code getting following output:- (currently reading 1 line simplicity)
01 sun oct 25 16:03:04 2015 john nice meeting
you!
one way use fgets()
read each line of file , sscanf()
parse each line. scanset %24[^\n]
read 24 characters stopping on newline. date format has 24 characters reads date. scanset %119[^\n]
reads 119 character prevent writing many characters message
, stops on newline. sscanf()
returns number of fields scanned 4 indicates line scanned successfully.
#include <stdio.h> #include <stdlib.h> #include <string.h> struct text { int no; char date[40]; char name[20]; char message[120]; }; int main( ) { char line[200]; struct text text = {0,"","",""}; file *pf = null; if ( ( pf = fopen ( "input.txt", "r")) == null) { printf ( "could not open file\n"); return 1; } while ( ( fgets ( line, sizeof ( line), pf))) { if ( ( sscanf ( line, "%d %24[^\n] %19s %119[^\n]" , &text.no, text.date, text.name, text.message)) == 4) { printf ( "%d\n%s\n%s\n%s\n", text.no, text.date, text.name, text.message); } } fclose ( pf); return 0; }
Comments
Post a Comment