Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
225 views
in Technique[技术] by (71.8m points)

fopen() not working in C

I got it fixed. Thanks for all the help.

I've now looked through quite a few articles, forum posts and topics here; however, none have actually fixed my issue. The problem is that my fopen("file.txt", "w"); doesn't create the file.

Code:

//
//Includes
#include <stdio.h>

int main ()
{
    FILE *receipt = fopen("receipt.txt", "w");

    //Create file
    fprintf(receipt, "Price: %.2f$", purchase);
    fprintf(receipt, "
Discount: %.2f$", discount);
    fprintf(receipt, "
Tax %%: %.2f%%", tax_pct);
    fprintf(receipt, "
Taxes: %.2f$", tax);
    fprintf(receipt, "
Total Price: %.2f$", end_price);
    fprintf(receipt, "

End of Receipt.");
    fclose(receipt);

    return 0;
}

I've tried throwing in

if(!receipt) {
    printf("Error!");
}
else {
    fprintf(blabla);
}

But to no avail.

It simply does not create the file :/ Running in Xcode and on Mac. No warnings/notices or otherwise stuff to give me any idea of what is wrong.

*I tried adding system("pwd") to figure out if it didn't save it where it should save it, but I have a hard time actually finding that directory (I don't know if it's temp, but even so the file should be there?). Obviously I wasn't questioning the actual validity of the library, duh, implicit that it was the fopen I was using not giving me what I expected?

I can't make perror give me any useful information. Everything would appear to work as it should; I just don't get a file. Please avoid any more smartass comments, if you don't want to help just don't write.*

Also, I removed all code, but the actual fopen() and fprintf().

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The only explanations that makes sense are that you don't have permissions to create the file in the working directory, or the working directory is not where you are looking for the file to be created.

fopen() not working

Well, of course it works. You shouldn't get in the mindset that the standard library doesn't work.

No warnings/notices or otherwise stuff to give me any idea of what is wrong.

You did not check for errors after calling fopen(). If you don't check for errors, how do you expect them to be delivered to you?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...