hi, i am new in c programming. i am making a program that will receive text from a file. but it stops taking string when there is 'new line'.what condition i have to put to get all the strings from a file. my codes are given below. char read_file (char ch[]) { FILE* read_file; char gets_name[14]; printf ("PLEASE ENTER THE FILE NAME TO READ AND ENCODE:"); scanf("%s", gets_name); read_file=fopen (gets_name,"r"); fgets (ch,1000,read_file); printf("\n\nYOUR FILE CONTAINS FOLLOWING TEXT: \n"); printf ("-----------------------------------\n"); printf ("%s\n\n",ch); please help me. thnks in advance
Code: char buffer[100]; while(fgets(buffer, sizeof buffer, read_file) != NULL) { ... printf ... } or while(fscanf(read_file, "%s", buffer) == 1) { ... printf ... } fgets will leave the newline in "buffer". If that isn't wanted Code: while(fgets(buffer, sizeof buffer, read_file) != NULL) { char *p = strchr(buffer, '\n'); if(p != NULL) *p = '\0'; ... printf ... } fscanf breaks on white space; basically, it reads words and not lines whereas fgets reads lines. Well up until the newline is encountered or size of the buffer is exceeded. HTH
thank you so much. using your given code, I am able to print all string but I it prints from a new line it erases previous line from 'ch' and saves new line string even if it prints every line one by one. what can I do to save all lines string in 'ch' thanks again
chepe dhorco. Ami there komor japte dhore tmr sharir niche voda ta mukhe nie prochondo Jore chushe khacci. tmi jeno matal hoye ar darie thakte parco na. Amk tene bed a shuie Amr upor uthe pagol er moto thot chushe khacco. 2jon 2jon er jiv chushci. thot khete khete Tmr blouse khule felci. Tmi Amr gale Tmr dudh bulie dicco. Ami Tmr Dudh er ordhek ta kamre dhore khub chushci. tmk bed a fele Dudh 2 ta kamre chushe khacci ar tmr shari khule felci
if you're asking about storing each line from the file into a variable, then you'll need a 2d array or perhaps a linked list if you don't know how many lines ahead of time you'll have. Code: char saved[number_of_lines][1000]; int index = 0; while(fgets(ch, 1000, read_file) != NULL) { // newline stored in ch (remove it before strcpy if desired) strcpy(saved[index], ch); ++index; } Are you sure you need to store each line in a variable?