0
int i=0;
int numProgs=0;
char* input[500];
char line[500];
FILE *file;
file = fopen(argv[1], "r");
while(fgets(line, sizeof line, file)!=NULL) {
    /*check to be sure reading correctly
    add each filename into array of input*/
    input[i] = (char*)malloc(strlen(line)+1);
    strcpy(input[i],line);
    printf("%s",input[i]);/*it gives the hole line with\n*/
    i++;
    /*count number of input in file*/
    numProgs++;
}
/*check to be sure going into array correctly*/
fclose(file);

I don't know the size of the input txt for each line so i need to do it dynamically. I need to use char* input[] this type of array and also i need to hold line numbers with int numProgs. Input text file has multiple lines and each line has unknown size of character.

fulladder
  • 1
  • 3
  • 1
    Possible duplicate: http://stackoverflow.com/questions/8236/how-do-you-determine-the-size-of-a-file-in-c – schil227 Nov 22 '16 at 14:23
  • You call allocate memory for say `char *line` instead of having a fixed array. After calling `fgets` check to see if a `newline` was read. If it was, you got the whole line. If not, reallocate a larger array, and read some more, as many times as necessary to get the whole line. But do not `free(line)` after each full line - just keep the allocation until you have done. – Weather Vane Nov 22 '16 at 14:24
  • @schil227 this Q is count of lines of file. – BLUEPIXY Nov 22 '16 at 14:28
  • Then perhaps http://stackoverflow.com/questions/2137156/finding-line-size-of-each-row-in-a-text-file - basically going through each character until a end of line character is found (\n) – schil227 Nov 22 '16 at 14:31
  • 1
    Note: use a `struct` for related variables. Seperate arrays for each components is soo 60ies/70ies – too honest for this site Nov 22 '16 at 14:31
  • use "wc -l filename" to get all line number before fgets and then you can initialize your input variable. – Sumit Gemini Nov 22 '16 at 15:53

1 Answers1

0
FILE *file;
file = fopen("test.txt", "r");
fseek(file, 0, SEEK_SET);
int numRow = 1, c;
while ((c = fgetc(file)) != EOF)
{
    if (c == '\n')
        numRow++;
}
fseek(file, 0, SEEK_SET);
char **input;
input = malloc(sizeof(char) * numRow);
int i, j = 0, numCol = 1, curPos;
for (i = 0; i < numRow; i++)
{
    curPos = (int)ftell(file);
    while((c = fgetc(file)) != '\n')
    {
        numCol++;
    }
    input[i] = malloc(sizeof(char) * numCol);
    fseek(file, curPos, SEEK_SET);
    while((c = fgetc(file)) != '\n')
    {
        input[i][j++] = c;
    }
    input[i][j + 1] = '\n';
    numCol = 1;
    j = 0;
}