Sunday, July 12, 2009

How to read a textfile line by line to an array in c language?

how can i read a variable size textfile line by line to an array of strings in c language

How to read a textfile line by line to an array in c language?
its done by fgets() function in C








#include %26lt;stdio.h%26gt;





void stripnl(char *str) {


while(strlen(str) %26amp;%26amp; ( (str[strlen(str) - 1] == 13) ||


( str[strlen(str) - 1] == 10 ))) {


str[strlen(str) - 1] = 0;


}


}


int main()


{


FILE *infile;


char fname[40];


char line[100];





/* Read in the filename */


printf("Enter the name of a ascii file: ");


fgets(fname, sizeof(fname), stdin);





/* We need to get rid of the newline char. */


stripnl(fname);





/* Open the file. If NULL is returned there was an error */


if((infile = fopen(fname, "r")) == NULL) {


printf("Error Opening File.\n");


exit(1);


}





while( fgets(line, sizeof(line), infile) != NULL ) {


/* Get each line from the infile */





/* print the line number and data */


printf(" %s", line);


}





fclose(infile); /* Close the file */


}


No comments:

Post a Comment