Nathaniel King
Nathaniel King

Reputation: 29

I can't get my file to be read and printed properly in C, only prints out '0'

struct patient getPatient(FILE *fptr)
{
    char fileInput[200];
    int noOfEntries = 0, n;
    while (!feof(fptr))
    {
        fscanf(fptr, "%499[^\n]*s", fileInput);

        for (n = 0; n < FILENAME; n++ )
        {
        printf("%500c\n", fileInput);
        }
    }
}

This is where the file is being read, and I open it in another function.

FILE *openFile(void)
{
    FILE *fptr;
    char filename[FILENAME];
    printf("Enter filename: ");
    scanf("%s", filename);
    if (!(fptr = fopen(filename, "r")))
    {
        printf("Can't open file %s", filename);
        exit(1);
    }
    return fptr;
}

And they are both called here.

FILE *fptr = openFile();
getPatient(fptr);

It's either being opened incorrectly or not read correctly, I am reading it to a struct.

struct patient
{
    char entryLine[500];
};

EDIT: The new code, this block is more self-contained than last time I think.

void showPatientDetails(char fileName[70])
{
    char fileInput[500];
    int n;
    FILE *fptr;
    if(!(fptr = fopen(fileName, "r")))
    {
        printf("\n\nUnable to open files! \n\n");
        exit(1);
    }
    while(fgets(fileInput, sizeof fileInput, fptr))
    {
        fscanf(fptr, "%499[^\n]", fileInput);
        printf("%500c\n", fileInput);
//      for (n = 0; n < FILENAME; n++ )
//        {
//            printf("%500c\n", fileInput);
//        }
    }
}

I've tried two methods, one we did yesterday and another one that my teacher used for something else.

Upvotes: 0

Views: 66

Answers (1)

unwind
unwind

Reputation: 399703

You seem to suffer from the magically common misconception that %[] somehow works as a modifier for a subsequent s. It really doesn't, it is its own conversion specifier.

So your conversion will fail unless the linefeed(s) are followed by an asterisk and an s.

Upvotes: 3

Related Questions