#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    How to read a text file into an array of strings?


    In a program, I have a text file (called MyDictionary.txt) which has thousands of words in alphabetical order. I need to make a C program that reads in this text file and then makes an array called

    char Words[# of total words in the text file][length of longest word].

    How do i do that??

    if it helps, this is kind of what the dictionary looks like, except many more words:

    Aarhus
    Aaron
    Ababa
    aback
    abaft
    abandon

    if you could give me exactly how to do this that would be great, because I have very little time. Thanks for all the help.
  2. #2
  3. Contributed User
    Devshed Specialist (4000 - 4499 posts)

    Join Date
    Jun 2005
    Posts
    4,417
    Rep Power
    1871
    Well the simple way is to read the whole file once, just to count the number of words and find the longest.

    When you know this, you allocate your array, use the rewind() function to reset the file back to the start, and then read the words into your array.

    cross-posting dweeb
    Last edited by salem; March 4th, 2013 at 02:52 AM.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    17
    Rep Power
    0
    Try this out:

    Code:
    #include<stdio.h>
    #include<string.h>
    
    void write() //you can skip this function. Just for writing in the file
    {
    	FILE *people = fopen("people.txt","w");
    	fprintf(people,"%s\n%s\n%s\n%s\n%s\n%s\n%s\n%s\m%s\n","Allie ","Tommy ","Jacob ","Shelby ","Waldo ","Timmy ","Bob ","Brett ","Mario ");
    	fclose(people);
    }
    
    void output()
    {
    	int size = 0;
    	char peeps[10000][10];
    	FILE *people = fopen("C:\\Users\\mineJons\\Documents\\Visual Studio 2010\\Projects\\hello world1\\hello world1\\people.txt","r");
    	while(fscanf(people,"%s",peeps[size]) != EOF)
    	{
    		++size;
    	}
    	fclose(people);
    	peeps[size][10];
    	printf("%s",peeps[8]);
    }
    
    int main()
    {
    	write();
    	output();
    	getchar();
    	return 0;
    }
    Not completey finished; you still have to sort the values but I think ya good after that. Unless it's not what you want (already works, tested it)

IMN logo majestic logo threadwatch logo seochat tools logo