C, Text file to array

Reading the lines of text into an array

Page 1 of 1

2 Replies - 3495 Views - Last Post: 05 February 2009 - 11:32 AM Rate Topic: -----

#1 Typewriter  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 01-October 08

C, Text file to array

Posted 05 February 2009 - 10:15 AM

Hi,

I'm using C to try and and open a file, then add the lines from the text file into an array one by one. Each would be delimited by the end of line character I think.

I am having the user select the name and location of the text file with scanf and the variable is being held b "userFile".
Then trying to read to an array called "usernames"


readUFile = fopen (userFile, "rt");

fread (usernames, LenOfusernames, 1, readUFile);




Am I going about this the right way or am I better off trying to use to use this or some other call? I'm not very familiar with the options that C has for this sort of thing so I don't even know if I have used fread correctly.

Any suggestions to point me in the right direction would be a great help.

Thanks

Is This A Good Question/Topic? 0
  • +

Replies To: C, Text file to array

#2 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5949
  • View blog
  • Posts: 23,206
  • Joined: 23-August 08

Re: C, Text file to array

Posted 05 February 2009 - 11:13 AM

You should use fgets rather than fread.
Was This Post Helpful? 0
  • +
  • -

#3 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 275
  • View blog
  • Posts: 1,764
  • Joined: 20-September 08

Re: C, Text file to array

Posted 05 February 2009 - 11:32 AM

View PostJackOfAllTrades, on 5 Feb, 2009 - 10:13 AM, said:

You should use fgets rather than fread.


Here is a small demo ...

#include <stdio.h>

#define maxLen 255 /* make this bigger than your longest line length ... */

int main()
{
    FILE *fp;
    char buf[maxLen+1]; /* +1 for the '\0' char that terminates C strings ... */
    
    /* open the file */
    fp = fopen( "data.txt", "r" );
    if(fp == NULL)
    {
         printf("Error opening 'data.txt' ... \n");
         getchar();
         return 1;
    }
    
    /* read file line by line and display ... */
    
    /* Note: '\n' char at the end of each line is included, if buffer big enough */
    while( fgets(buf, maxLen+1, fp) )
    {
        printf( "%s", buf ); 
    }
    fclose( fp );
    
    printf( "\nPress 'Enter' to exit ... " );
    getchar();
    return 0;
}

/*
An example data.txt

Breakfast Cafeteria 5.75
Lunch RZ's 10.25
Dinner Restaurant 20.15
Breakfast Cafeteria 4.44

Lunch Restaurant 11.75
Dinner Restaurant 12.23
Lunch Restaurant 10.25
Breakfast RZ's 7.35
*/



This method though, will cause some problems, if you want to store each 'line', without the '\n' char at the end of each line ... in an array ... AND a BIGGER problem, if you happen to have a line in your file that is TOO long for your buffer with a pre-set max-length at compile time.

A way to handle this in C, is to use dynamic memory, adjusted individually, to each line length ... and also for the array to hold all your C strings of lines ...

/*
    ... assignment:

    * Read in data from a .txt file line by line
    * Store each line in a C-String
    * Create a new dynamically allocated array and read the lines into it
    * and dsiplay ...

*/

#include <stdlib.h>
#include <stdio.h>
#include <string.h> /* for strlen(...) */

typedef char* CString; /* CString is type 'pointer to char' ... */

/* returns NULL for EOF ... or a pointer to a NEW CString ... */
CString readLine(FILE* f)
{
    static int c = 0; /* static ... to remember if a previous call set EOF */
    static int lineCount = 0; /* to handle the empty file ... */
    int bufSize = 255, i = 0; /* adjust 255 to whatever is 'right' for your data */

    if(c == EOF) {c=0; lineCount=0; return NULL;} /* reset so can rewind and read again */

	CString line = (CString) calloc(bufSize, sizeof(char));

	while ((c = fgetc(f)) != EOF && c != '\n')
	{
        if(i >= bufSize)
        {
            bufSize += 256; /* adjust 256 to whatever is 'right' for your data */
            line = (CString) realloc(line, bufSize*sizeof(char));
        }
        line[i++] = c;
	}
	/* handle special case of empty file ...*/
	if(lineCount++ == 0 && c == EOF) {free(line); return NULL;}

	line[i] = '\0'; /* confirm terminal 0 */
	return realloc(line, i+1); /* total len =  last index i ... + 1 more */
}

int main()
{
    CString cs, *csAry;
    int i=0, j=0;
    FILE * fp;
    fp = fopen("data.txt", "r");
    if( fp == NULL )
    {
        printf("Error opening file. Press 'Enter' to exit ... ");
        getchar();
        return 1;
    }

    puts("First pass ... counting lines of text and showing each line ...");
    while( (cs = readLine( fp )) )
    {
        ++i;
        printf("%d: %s\n", i, cs);
        free(cs);
    }

    rewind( fp );
    
    /* now reserve sufficent memory for an array of pointers to CStrings ... */
    csAry = (CString*) malloc( i*sizeof(CString) );
    
    /* now read the file into the array of CStrings ... */
    while( (cs = readLine( fp )) )
        csAry[j++] = cs;
    
    fclose(fp);
    
    if( i != j )
        printf("\nError reading file i=%d, but j=%d\n", i, j );
    
    
    puts("Now ... displaying the dynamic array ...");
    for( j=0; j<i; ++j)
    {
        printf("%d: %s\n", j+1, csAry[j]);
        free( csAry[j] ); /* free memory reserved for each CString when done with it */
    }
    free( csAry ); /* free memory reservered for the array when done with it */

    printf("Press 'Enter' to continue ...");
    getchar();
    return 0;
}

/*
Sample File: data.txt

Breakfast Cafeteria 5.75
Lunch RZ's 10.25
Dinner Restaurant 20.15
Breakfast Cafeteria 4.44

Lunch Restaurant 11.75
Dinner Restaurant 12.23
Lunch Restaurant 10.25
Breakfast RZ's 7.35
*/


Shalom,
David

This post has been edited by David W: 05 February 2009 - 11:52 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1