tags:

views:

222

answers:

4

Hi to all, I have a text file and i want to to read it line by line and put the lines into an array.

The snippet behind gives error while compiling:

FILE *f;
char line[LINE_SIZE];
char *lines;
int num_righe;

f = fopen("spese.dat", "r");

if(f == NULL) {
 f = fopen("spese.dat", "w");
}

while(fgets(line, LINE_SIZE, f)) {  
 num_righe++;
 lines = realloc(lines, (sizeof(char)*LINE_SIZE)*num_righe);
 strcpy(lines[num_righe-1], line);
}

fclose(f);

The error is:

spese.c:29: warning: assignment makes integer from pointer without a cast
spese.c:30: warning: incompatible implicit declaration of built-in function ‘strcpy’
spese.c:30: warning: passing argument 1 of ‘strcpy’ makes pointer from integer without a cast

Any help? Thanks

+2  A: 

I take this is a code snipet, consequently, i guess that you are alredy including string.h

strcpy is defined as:

  char * strcpy ( char * destination, const char * source );

In

 strcpy(lines[num_righe-1], line);

lines [num_righe-1] is a char, not a char*

So it should be

strcpy(lines + (num_righe-1), line);

As munificent wrote, it looks like you are trying to make lines an array of strings. If so, your definition of lines is wrong.

Also, dont forget, you should check that realloc doesn't return NULL.

lines = realloc(lines, (sizeof(char)*LINE_SIZE)*num_righe);

if (!lines) //MUST HANDLE NULL POINTER!!

/* string copy code here*/
Tom
Aren't these statements identical?
samoz
Emil H
There is no need to cast when using realloc.
anon
@Neil. I was dubitative about that one. It's gone.
Tom
+1  A: 

lines is a pointer to a character, i.e. a single string. You want it to be an array of strings. For that, it should be char **lines;

munificent
A: 

You can use fscanf instead to do what you want.

fscanf(f, "%s\n", line[index]);
index++;
samoz
+4  A: 

Try:

FILE *f;
char line[LINE_SIZE];
char **lines = NULL;
int num_righe = 0;

f = fopen("spese.dat", "r");

if(f == NULL) {
        f = fopen("spese.dat", "w");
}

while(fgets(line, LINE_SIZE, f)) {              
        num_righe++;
        lines = (char**)realloc(lines, sizeof(char*)*num_righe);
        lines[num_righe-1] = strdup(line);
}

fclose(f);
Emil H
isn't sizeof(char) always identical to 1 byte?
Tom
Yes. But my code uses sizeof(char*) which in general is 4 bytes, not 1.
Emil H
Oh, didn't notice that *. I apologize.
Tom
Don't worry about it. Can happen to anyone. :)
Emil H
it worked, thank you very much :)
pistacchio
Actually, strdup CAN return NULL. You might want to take that into account. In addition to that, you should remember to free that memory once you are done (strdup uses malloc)
Tom