0

The program runs and can successfully write to a text file, but when I try to read back from the text file I get:

"Exception thrown at 0x0F8C7071 (ucrtbased.dll) in Text Files Homework.exe: 0xC0000005: Access violation writing location 0xFFFFFFCC."

Which brings me to line 1092 in stdio.h.

The code inside the function that is supposed to read each line is: Product temp;

char name[MAX_STRING_LEN];
char type;
double price;
int qty;

int moreData = fscanf_s(stream, "%s", temp.name, MAX_STRING_LEN - 1);

if (moreData != EOF)
{

    fscanf_s(stream, "%c", temp.type);
    fscanf_s(stream, "%lf", &temp.price);
    fscanf_s(stream, "%d", &temp.qty);

    // echo what just got read (from the file) to the console.
    printf_s("%s %c %.2f %d was read \n\n", temp.name, temp.type, temp.price, temp.qty);
}
else
{
    printf("Read past end of file.\n\n");
}
*pro = temp;
return moreData;

And the function that calls that function is:

FILE *stream;
Product p;
*numProducts = 0;

int err = fopen_s(&stream, fileName, "r");
if (err)
    printf_s("File %s was not opened for reading. \n", fileName);
else {

    printf("\n\nReading Product data from file... \n");

    // Read data back from file:  
    int moreData = readLine(stream, &p);
    while (moreData != EOF) {
        printf("Number of products was %d ", *numProducts);
        reportLine(p);
        list[*numProducts] = p;
        *numProducts = *numProducts + 1;
        printf("It is now incremented to %d \n", *numProducts);
        moreData = readLine(stream, &p);
    }

    fclose(stream);
}
K.Dᴀᴠɪs
  • 9,945
  • 11
  • 33
  • 43
  • Need an [MCVE](https://stackoverflow.com/help/mcve) – MFisherKDX Apr 09 '18 at 20:43
  • 2
    You're missing a `&` in `fscanf_s(stream, "%c", temp.type);` => `...&temp.type...` – Flopp Apr 09 '18 at 20:58
  • One point, `fscanf_s(stream, "%c", temp.type);` needs a space before `%c` as in hundreds of questions/answers such as [scanf() leaves the new line char in the buffer](https://stackoverflow.com/questions/5240789/scanf-leaves-the-new-line-char-in-the-buffer), as well as the missing `&` mentioned above. – Weather Vane Apr 09 '18 at 20:58
  • Aside: Microsoft VC tries to force you to use their non-standard functions. Don't go there. – Weather Vane Apr 09 '18 at 21:03
  • Moreover `fscanf_s(stream, "%c", temp.type);` is missing the required **size** argument. *Unlike `scanf` and `wscanf`, `scanf_s` and `wscanf_s` require the buffer size to be specified for all input parameters of type `c`, `C`, `s`, `S`, or string control sets that are enclosed in `[]`. The buffer size in characters is passed as an additional parameter immediately following the pointer to the buffer or variable.* – Weather Vane Apr 09 '18 at 21:06

0 Answers0