5 Replies - 4751 Views - Last Post: 26 February 2011 - 05:52 AM Rate Topic: -----

#1 jingoria  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 96
  • Joined: 22-October 07

C++ program to read file into array

Posted 25 February 2011 - 03:13 PM

Hi, I was browsing DIC and trying understand a program written by 'David W' in one of the threads.
I was trying to understand the code since my program needs to use same sort of logic. But when I tried compiling the program provided by 'David W', I got an error which I do understand but don't know how to avoid. Here is the code:




    ... 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

    * Find out how long each line is using strlen()

    * After all the lines are read in, sort the array of lines by line length
009
*/

 

#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 */

    [color="#FF0000"]return realloc(line, i+1); /* total len =  last index i ... + 1 more */
[/color]
}

 

void sortByStrLen( CString a[], int num )

{

    int i=0, j, swap;

    CString temp;

    do

    {

        swap = 0;

        for(j = 1; j < num-i; ++j) /* then swap */

        {

            if(strlen(a[j-1]) > strlen(a[j])) /* swap pointers */

            {

                temp = a[j];

                a[j] = a[j-1];

                a[j-1] = temp;

                swap = 1;

            }

        }

        ++i;

    }while(swap);

}

 

 

int main()

{

    CString cs;

    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;

    }

 

    /* first pass count lines of text and show ... */

    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 ... */

    CString * 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("\nSorted by length ...\n");

 

    sortByStrLen( csAry, i );

     

    for( j=0; j<i; ++j)

    {

        printf("%d: %s\n", j+1, csAry[j]);

        free( csAry[j] ); /* free memory reserved for each CString */

    }

    free( csAry ); /* free memory reservered for the array ... */

 

    printf("Press 'Enter' to continue ...");

    getchar();

    return 0;



The error I receive is due to line (in red): return realloc(line, i+1); /* total len = last index i ... + 1 more */

Error: invalid conversion from `void*' to `char*'
because realloc() is a void function which is being passed to function of type char.

Please if anyone can explain me how I can correct this or work around.
I changed it to return 0, so the program does compile but it reads only one line from the text file instead of reading the whole file.

Thankyou.


}

This post has been edited by jingoria: 25 February 2011 - 03:18 PM


Is This A Good Question/Topic? 0
  • +

Replies To: C++ program to read file into array

#2 simeesta  Icon User is offline

  • Deadly Ninja


Reputation: 219
  • View blog
  • Posts: 592
  • Joined: 04-August 09

Re: C++ program to read file into array

Posted 25 February 2011 - 03:31 PM

You can cast it to char* using return (char*) realloc(line,i+1);
Was This Post Helpful? 0
  • +
  • -

#3 jingoria  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 96
  • Joined: 22-October 07

Re: C++ program to read file into array

Posted 25 February 2011 - 04:02 PM

View Postsimeesta, on 25 February 2011 - 03:31 PM, said:

You can cast it to char* using return (char*) realloc(line,i+1);


Thanks. I figured out. I did a typecast and had change to the second value of j in for loop to read whole file.

Thanks though.
Was This Post Helpful? 0
  • +
  • -

#4 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 6064
  • View blog
  • Posts: 23,518
  • Joined: 23-August 08

Re: C++ program to read file into array

Posted 25 February 2011 - 04:16 PM

Note that the reason you have to cast the return value here is because you're compiling this C program as C++. You would NOT need, nor SHOULD YOU, cast the return value were you compiling it as the C program it is.
Was This Post Helpful? 0
  • +
  • -

#5 jingoria  Icon User is offline

  • D.I.C Head

Reputation: 3
  • View blog
  • Posts: 96
  • Joined: 22-October 07

Re: C++ program to read file into array

Posted 25 February 2011 - 05:53 PM

View PostJackOfAllTrades, on 25 February 2011 - 04:16 PM, said:

Note that the reason you have to cast the return value here is because you're compiling this C program as C++. You would NOT need, nor SHOULD YOU, cast the return value were you compiling it as the C program it is.


Thanks for JackOfAllTrades. But I have another question. The code is reading only the first line of text. What I was trying to do is read all the lines of the file and I thought the EOF statement would take care of that.

Could you please tell me what changes would be required to achieve that. I looked couple of times over the code to understand but I am getting confused as I am used to c++ and not c.

Thanks.
Was This Post Helpful? 0
  • +
  • -

#6 David W  Icon User is offline

  • DIC supporter
  • member icon

Reputation: 281
  • View blog
  • Posts: 1,788
  • Joined: 20-September 08

Re: C++ program to read file into array

Posted 26 February 2011 - 05:52 AM

If you want a C++ style program, I suggest you start over using C++ string and a STL vector container to hold your strings. That C code you found should probably be dumped ... If I were to write that program in C these days, I would use my readLine.h file to use dynamic C strings of any length. Also I would probably use CvecOfString.h so I could use all the functions there to process C strings using a C++ like dynamic array ( vector ) container.

To sort a container of C++ strings by length is quite simple.

To compare if string s1 is 'less than' s2, you just compare s1.size() < s2.size()

To code you solution in C++ will be much easier and cleaner, if you stick with C++. If you don't know C (or allocating dynamic memory) the overhead to use that old C program is too excessive.

Check here for a C++ code start to your problem ...

http://www.dreaminco...ngwriting-file/

This post has been edited by David W: 26 February 2011 - 06:44 AM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1