phil
phil

Reputation: 253

How to read a string from a text file and store it in an array

I am working on a class project and I really need help. What I need to realize is to read two string from either one text file, or two separate files, and store them in two arrays respectively. The strings can be of any length, but do not have to be very long. The size of each array can be adjusted automatically according to the length of the corresponding string.

I've searched on Stack Overflow and got some codes, I was trying one which uses malloc(). But I had troubles when I was trying to get the size of the array.

int main(){
int i = 0;

int BUFSIZE = 1000;
char* string[20];
FILE *fp = fopen("input.txt", "r");
if (fp == 0){
    fprintf(stderr, "Error while opening");
    return 0;
}

string[i] = (char *)malloc(BUFSIZE);
while (fgets(string[i], BUFSIZE, fp)) {
    i++;
    string[i] = (char *)malloc(BUFSIZE);
} 

float len=sizeof(string);
printf("%f", len);  

int x;
for(x = 0; x<i; x++)
   free(string[x]);
scanf("%d", x);
fclose(fp);
return 0;
}

I tried to output len, but I got a constant value 80, no matter how long the string is. Besides, I don't know how to read two strings, and store them in two separate arrays. I got errors when trying to add another string into the codes.

Upvotes: 3

Views: 3940

Answers (2)

plaknas
plaknas

Reputation: 274

If you want the length of the string, then you need to use

strlen(string[i]);

What you are doing will simply return the size of string, which is indeed 80 (20*4).

Upvotes: 1

iabdalkader
iabdalkader

Reputation: 17332

This:

float len=sizeof(string);

Just gives you the static size of the array string which is an array of 20 pointers and each pointer is 4 bytes, 20 * 4 bytes = 80 that's why it's always 80. you already have the size of the array because you increment i for each string, that's the size of the array just print i by size I mean the number of strings you allocated in the array, or the number of lines in the file.

Edit: if you want to get the length of the string(s) in the array use strlen

while (fgets(string[i], BUFSIZE, fp)) {
    i++;
    len+=strlen(string[i]);
    string[i] = (char *)malloc(BUFSIZE);    
} 

Note: it should be int not float but that's not the point.

Upvotes: 2

Related Questions