0

I have accomplished getting my c program to read text line by line. That was the easy part or at least in my perspective. What i need to do now is to assign variables per line. For Example the first line of the text file would be equal to the variable line1.

Or this

char line1 = (text from line one)
char line2 = (text from line two)

My code thus far:

    char line[1000] = ""; 

    FILE *ifp;

    ifp = fopen("Tree-B.txt", "r");
    if (ifp == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }

    while (fscanf(ifp, "%s", line) == 1)
    {
        printf("%s ", line);
    }
    printf("\n");
    fclose(ifp);

    return 0;

I have absolutely no idea how to do this.

2 Answers2

1

You can use an array of pointer for that matter.

char line[1000] = "";  // assume each line has at most 999 chars (1 space for NUL character)
char *lines[1000] = { NULL }; // assume max number of lines is 1000
int idx = 0;
FILE *ifp;

ifp = fopen("q2.cpp", "r");
if (ifp == NULL)
{
    printf("Error opening file!\n");
    exit(1);
}

while(fgets(line, sizeof(line), ifp) != NULL)
{
    lines[idx] = strdup(line);
    printf("%s", lines[idx]);
    idx++;
}

Notes:

  • This approach using strdup which is POSIX (not official C standard). However, you can put in a publicly available strdup function itself.

  • fgets is preferred than fscanf so I changed it that way.

  • 1000 limis are suggestive - you can/should change those constants to what would make more sense in the program itself.

Community
  • 1
  • 1
artm
  • 17,291
  • 6
  • 38
  • 54
0
#include <stdio.h>

#define MAX_LINES 1000
#define MAX_LINE_LENGTH 200

int main()
{
    char fileContents[MAX_LINES][MAX_LINE_LENGTH];
    int lineCount = 0;

    FILE *ifp = fopen("Tree-B.txt", "r");
    if (ifp == NULL)
    {
        printf("Error opening file!\n");
        exit(1);
    }

    while (fgets(fileContents[lineCount++], MAX_LINE_LENGTH, ifp) != NULL);
    fclose(ifp);

    printf("File Contents:\n");
    for (int i = 0; i < lineCount-1; ++i)
    {
        printf("%s", fileContents[i]); // or fputs
    }

    return 0;
}

You can refer here, if you wish to dynamically allocate memory for fileContents.

Community
  • 1
  • 1
mac
  • 81
  • 5