Well, I wrote the code in post #2 as an example intended to be adapted, so I did not compile and test it, hence it is possible that it might contain a bug or two. I decided to write a program to test it:
Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Coord
{
int x;
int y;
};
int read_coords(FILE *fptr, struct Coord coords[], int max_num)
{
char header[BUFSIZ];
if (!fgets(header, BUFSIZ, fptr))
{
return -1;
}
if (strcmp(header, "x y\n") != 0)
{
return -1;
}
int num = 0;
while (num < max_num && fscanf(fptr, "%d %d", &coords[num].x, &coords[num].y) == 2)
{
++num;
}
return num;
}
void print_coords(FILE *fptr, const struct Coord coords[], int num)
{
fprintf(fptr, "x y\n");
for (int i = 0; i < num; ++i)
{
fprintf(fptr, "%d %d\n", coords[i].x, coords[i].y);
}
}
int main(void)
{
const char *filename = "input.txt";
FILE *fp = fopen(filename, "r");
if (!fp)
{
fprintf(stderr, "Error: could not open '%s'\n", filename);
return EXIT_FAILURE;
}
struct Coord coords[15];
int num = read_coords(fp, coords, 15);
if (num < 0)
{
fprintf(stderr, "Error: '%s' is missing the header or has an invalid header\n", filename);
fclose(fp);
return EXIT_FAILURE;
}
fclose(fp);
print_coords(stdout, coords, num);
return 0;
}
Using a file with this context as input.txt:
Code:
x y
5 7
15 4
7 2
10 6
Compiling and running the above program prints this result:
Code:
x y
5 7
15 4
7 2
10 6
which is exactly as expected, so there is no bug in my example from post #2 that would result in the lack of output you observed.
Therefore, if you want further help in debugging, I suggest that you post the smallest and simplest compilable program that demonstrates this lack of output that you're observing.
EDIT:
Originally Posted by
aidan4
the function actually doesn't return anything.
That's obviously false: it returns the number of coordinates successfully read so that the caller can then use that number when working with the array of coordinates. Or, if there is an error, it returns -1, hence you need to check that the function does not return -1 before you go on to use the coordinates read. You can see an example of how that is done in my code above.