I know this question has been asked a few times, but never in a way that helps me figure out my problem. Essentially, I am reading four text files, all single words separated by a new line, and wanting to store these in a char array. I first count the number of lines in the file and then create a new char array, but for the life of me, I cannot figure out how to get it to read correctly. The last two lines are just to test if it has read the entire file correctly and they always come back a NULL and the question mark symbol.
I want each line to be at the next index in the char array.
Any help would be awesome! Thank you 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");
do
{
ch = fgetc(myfile);
if(ch == '\n')
lines++;
}while(ch != EOF);
char contents[lines];
int i = 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]);
}
void main ()is invalid on hosted environments.lines++;occurs 3 times?char contents[lines];is an array ofchar. Too many errors in your code.rewind.rewind(), you may wantfor(i=0;i<lines;i++)orfor(i=0;i<=lines;i++)