0

I need to load the contents of a file into two string arrays. I tried the following and it is not working. file.txt contains 10 records and each record has two string values separated by whitespace.

CODE:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(void) {
    char line[12][20];
    FILE *fptr = NULL; 
    int i = 0;
    int tot = 0;

    fptr = fopen("file.txt", "r");
    char arr[20][20];

    while (fgets(line, sizeof(line), fptr)) {
        strcpy(arr[i],line);
        i++;
    }
    tot=i;
    for (int i=0; i<tot; i++) {
        printf("first value %s",arr[i][0]);
        printf("second value is %s",arr[i][1]);
        printf("\n");
    }
    return 0;
}
2
  • What is the size of line? Perhaps find that out to understand the problem Commented Nov 5, 2019 at 18:17
  • You can use strtok to split lines into strings. Commented Nov 5, 2019 at 18:24

3 Answers 3

1

If I understand correctly, you're trying to store data in a structure like:

{{"line1A", "line1B"}, {"line2A", "line2B"}, {"line3A", "line3B"}}

It looks like you need an array where each element consists of two arrays (strings), one for the first value and one for the second value on each line. If this is the case, you need a three dimensional array of chars.

In the example below I've declared arrayOfLines as array with 12 elements each of which has 2 arrays of chars (for your two values per line), with space for 20 chars in each string (NULL terminated char array)

There are some other problems with your code:

  • The first parameter for fgets() should be a char * - a pointer to a string buffer. Your code passes in a multi-dimensional array of chars.
  • Your while loop should continue until fgets returns NULL
  • You need to split each line into multiple strings
  • Check for buffer overruns when copying strings with strcpy()

In the example code I used strtok() delimited by a " " space character - you may need to play around with this - strtok can accept an array of chars to be used as a delimiter. In the example, I split the first string using the first space char, and the second string is delimited by the end of line.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(void) 
{
    // Array for 12 lines, each with 2 strings, each string max 20 chars
    // Adjust values as required.
    char arrayOfLines[12][2][20];

    FILE *fptr = NULL; 
    int i = 0;
    int tot = 0;
    fptr = fopen("file.txt", "r");
    // char arr[20][20]; not needed

    char line[20];
    while(fgets(line, sizeof(line) / sizeof(line[0]), fptr) != NULL)
    {
        // Rudimentary error checking - if the string has no newline
        // there wasn't enough space in line
        if (strchr(line, '\n') == NULL) {
            printf("Line too long...");
            return EXIT_FAILURE;
        }
        // Split string into tokens
        // NB: Check for buffer overruns when copying strings
        char *ptr1 = strtok(line, " ");
        strcpy(arrayOfLines[i][0], ptr1);
        char *ptr2 = strtok(NULL, "\n");
        strcpy(arrayOfLines[i][1], ptr2);
        i++;
    }

    tot=i; // Unecessary - just use a different variable in your loop and use i as the upper bound

    for (int i=0;i<tot;i++)
    {
        printf("first value %s\n", arrayOfLines[i][0]);
        printf("second value is %s\n", arrayOfLines[i][1]);
        printf("\n");
    }

    return 0;
}
Sign up to request clarification or add additional context in comments.

Comments

0
printf("first value %s",arr[i][0]);
printf("second value is %s",arr[i][1]);

Basicly all you are doing is printing 2 chars from i word when you want to print full string you should do it like this: printf("%s",arr[i]); You said that value is separated by whitespace so when you are getting line from file you will save it to arr[i] (if first line in file contains "Hello World", your arr[0] will contain "Hello World") when you want to split it into 2 printf you need to print them char by char until space.

Edit: I reminded myself about function sscanf you can use it to get data from file array like you whould do it with keyboard input

Comments

0

You can use this to do that

Code

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main(void){

    char line[12][20];
    char arr[20][20];
    FILE *fptr=NULL; 
    int i=0;

    fptr = fopen("file.txt", "r");
    if(!fptr){
        printf("cant open file\n");
        exit(1);
    }

    while(fgets(*line, sizeof(line), fptr)){
        strncpy(arr[i],*line, sizeof(*line));
        i++;
    }

    for (int j=0;j<i;j++){
        printf("%s\n", arr[j]);
    }

    return 0;
}

Notes and changes I made on your code:

  • Check fptr as return value of open() if it's NULL decide what to do.
  • Remove unnecessary tot variable and use another index j in last for loop.
  • Use strncpy() as a better version of strcpy()
  • Correct way of print arr, printf("%s\n", arr[j]);
  • \n can be embed on first printf()

1 Comment

Why *line? Why is it [12][20] is you only use the first one?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.