fopen - Read txt file line by line into char array C -
i know question has been asked few times, never in way helps me figure out problem. essentially, reading 4 text files, single words separated new line, , wanting store these in char array. first count number of lines in file , create new char array, life of me, cannot figure out how read correctly. last 2 lines test if has read entire file correctly , come null , question mark symbol.
i want each line @ next index in char array.
any awesome! thank ahead of time.
#include <omp.h> #include <stdio.h> #include <stdlib.h> void countanagrams(char* filename); void main () { char *filenames[] = {"anagrama.txt","anagramb.txt","anagramc.txt","anagramd.txt"}; countanagrams(filenames[0]); countanagrams(filenames[1]); countanagrams(filenames[2]); countanagrams(filenames[3]); } void countanagrams(char* filename) { int anagramcount = 0; int ch, lines = 0; //count number of lines in file file *myfile = fopen(filename, "r"); { ch = fgetc(myfile); if(ch == '\n') lines++; }while(ch != eof); char contents[lines]; int = 0; for(i=1;i<lines;i++) { fscanf(myfile,"%s",contents[i]); } fclose(myfile); printf("%.12s\n",filename); printf("number of lines: %d\n", lines); printf("first thing: %s\n", contents[0]); printf("last thing: %s\n", contents[lines-1]); }
here's slight modification of code might you.
the main points:
- you can use
getline()
instead offscanf()
.fscanf()
can used read line-by-line, needs explicit check end of line condition.getline()
automatically. as kaylum pointed out, it's necessary
rewind()
file pointer beginning of file after counting number of lines.#include <omp.h> #include <stdio.h> #include <stdlib.h> void countanagrams(char* filename); void main () { char *filenames[] = {"anagrama.txt","anagramb.txt","anagramc.txt","anagramd.txt"}; countanagrams(filenames[0]); countanagrams(filenames[1]); countanagrams(filenames[2]); countanagrams(filenames[3]); } void countanagrams(char* filename) { int anagramcount = 0; int ch, lines = 0; //count number of lines in file file *myfile = fopen(filename, "r"); { ch = fgetc(myfile); if (ch == '\n') lines++; } while (ch != eof); rewind(myfile); char *contents[lines]; int = 0; size_t len = 0; for(i = 0; < lines; i++) { contents[i] = null; len = 0; getline(&contents[i], &len, myfile); } fclose(myfile); printf("%.12s\n",filename); printf("number of lines: %d\n", lines); printf("first thing: %s\n", contents[0]); printf("last thing: %s\n", contents[lines-1]); }
Comments
Post a Comment