Question Details

No question body available.

Tags

arrays c string file-handling

Answers (2)

Accepted Answer Available
Accepted Answer
July 5, 2025 Score: 0 Rep: 133 Quality: High Completeness: 60%

First of all, thank you for the feedback and I apologize for perhaps not being as clear as I could have been nor giving as much information as I should have. Indeed, the critical fault lied in the requested source file. Originally the .txt file looked something like this:

555555555555553333333333333333310100000000000000000111000001333333333333333333334333343

When coming up with the method I naïvely just copied what was given to me rather than fully understanding what was going on. Even a surface level understanding of strtok() would have likely prevented this simple mistake. strtok()'s second input is a delimiter which the function needs to properly separate the string of chars into ints, after all how would it know if the first number was 5 or 5555? Now knowing this I edited the file to look more like this:

5 5 5 5 5 5 5 5 5 5 5 5 5 5 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 1 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 1 0 0 0 0 0 1 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 3 4 3 3 3 3 4 3

Now, strtok(lineBuffer, " ") properly separates and stores the numbers as individual integers rather than one enormously long number which I believe is what was happening.

Now, as far as I'm aware everything is working as intended with that fix to the file. However--and maybe this is a question for a separate post--Many commented or at least illuded against using fgets() as a method to read a file. Initially why I chose this was so that I could perhaps store multiple arrays in one file instead of needing a separate file I could just choose which line to read in one file. I was thinking this might make things cleaner, but if this can be achieved just as well and with better reliability using a different method, I'd be open to it.

July 4, 2025 Score: 2 Rep: 81,542 Quality: Medium Completeness: 100%

fgets has these parameters:

  • str: the pointer to an element of a char array
  • count: the number of characters to read
  • stream: the data source

Inside your loop you are calling it like this:

fgets(lineBuffer, sizeof(lineBuffer), file);

and then split it into tokens by space and convert it via atoi. At the end you need to output along with space too, because you are merging the numbers together in the output:

            for (int j = 0; j < i; j++) {
                printf("%d ", array[j]);
            }

Instead you could simply load stuff, like this:

    FILE* ptr = fopen(fileName, "r");
    if (ptr == NULL) {
        printf("no such file.");
        //return some error code
    }

while (fscanf(ptr,"%d", &array[i++]) == 1);