开发者

problem using fprintf

I'm trying to print to a text file numerous variables yet it doesn't work. I checked and verified that i write it in the correct syntax. I also checked the return value and it's positive therefore i know it did write to the file, however when i open the file it's empty.

I would be happy for some help. This is the code:

I initiate DynsaleDayPtr in the main:

FILE* DynsaleDayPtr = CreateTextFiles("sale_day.txt");  

Create function:

FILE* CreateTextFiles (char* fileName)  
{  
    FILE* saleFilePtr=NULL;  

    if((saleFilePtr=fopen(fileName,"a+"))==NULL)  
        printf("File couldn't be opened\n");  
    return saleFilePtr;  
}  

The call to the function TextAddSale is done from a function that is called in the main:

TextAddSale(DynSaleDayPtr,dynNumOfRecords);

Bool TextAddSale (FILE* DynsaleDayPtr, int* dynNumOfRecords)  
{  

    char id[6];  
    char name [50];  
    char priceChar[20];  
    char* tmp = NULL;  
    int price=-1;  
    DynamicRecord * newRec=NULL;  

    scanf("%s%s%s",id,name,priceChar);

    newRec = (DynamicRecord *)malloc(sizeof(Dynamic开发者_如何学CRecord));  
    if (newRec == NULL)  
        return False;  
    tmp = (char*)malloc(strlen(name)+1);  
    if (tmp == NULL)  
    {  
        free (newRec);  
        return False;  
    }  
    strcpy(tmp,name);  
    newRec->productName = tmp;  
    strcpy(newRec->productId, id);  
    newRec->productPrice=atoi (priceChar);  

    if (fprintf(DynsaleDayPtr,"%d %s %s %d", strlen(newRec->productName),  
    newRec->productId, newRec->productName, newRec->productPrice)>0)  
    {  
        *dynNumOfRecords=(*dynNumOfRecords)+1;  
        return True;  
    }  
}

thanks!


You need to flush the stream.

fflush(FILE*);

Of course, you have to close the stream if you have done with it.

fclose(FILE*);


Agree with @pmg - try something like this:

FILE *pFile = fopen("foo.txt","w");
if (pFile==NULL)
   bad();
fprintf(pfile,"Hello world\n");
fclose(pfile);

make that work first - then fix whatever's wrong in the big app -


A thought:

scanf("%s%s%s",id,name,priceChar);

the above statement is a bit dodgy since you haven't said how many bytes should go in each string.

better to use fgets() then parse the string retrieving the individual values or create a better format specifier.

If the above statement causes a memory overwrite the rest of your program could malfunction causing things like what you describe.


fprintf() most likely uses buffered output. Therefore, you should either fflush() the DynSaleDayPtr stream or, better yet, print a newline to the file. The latter has the added benefit of making the file contents actually readable...

Also, don't forget to close() the stream when you're finished with writing. This will also render fflush() unnecessary.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜