C编程求助,如何使用C中的fopen和fprintf函数将给定的输出保存在文本文件中?

标签 c printf fopen

上次我编写此代码时,它运行良好。我希望将输出保存到文本文件中(通过 fprintf() 打印的任何内容)。现在,当我尝试再次运行代码时,它不会将输出保存在给定的文本文件 draftday.txt 中。任何帮助将不胜感激。

#include <stdio.h>
#include <conio.h>
#include <cstdlib>

int main()
{ 
    struct date
    {
        int day;
        int month;
        int year;
    };

    struct details
    {
        char name[50];
        int price;
        int code;
        int qty;
        struct date mfg;
    };

    struct details item[50];
    int n,i;

    getch();

    fflush(stdin);
    printf("Enter number of items:");
    scanf("%d",&n);     

    for(i=0;i<n;i++)
    {
        fflush(stdin);
        printf("Item name:");
        scanf("%[^\n]",item[i].name);

        fflush(stdin);
        printf("Item code:");
        scanf("%d",&item[i].code);

        fflush(stdin);
        printf("Quantity:");
        scanf("%d",&item[i].qty);

        fflush(stdin);
        printf("price:");
        scanf("%d",&item[i].price);

        fflush(stdin);
        printf("Manufacturing date(dd-mm-yyyy):");
        scanf("%d-%d-%d",&item[i].mfg.day,&item[i].mfg.month,&item[i].mfg.year);
    }

    {
    FILE *fptr;
    fptr=(fopen("draftday.txt","w"));
    if(fptr==NULL){
       printf("Error!");
       exit(1);
    }

    fprintf(fptr,"             *****  INVENTORY *****\n\n\n"
                 "------------------------------------------------------------------\n\n"
                 "S.N.|    NAME           |   CODE   |  QUANTITY |  PRICE  |MFG.DATE\n\n"
                 "------------------------------------------------------------------\n\n");


    for(i=0;i<n;i++){
        fprintf(fptr, "%d     %-15s        %-d          %-5d     %-5d       %d/%d/%d\n",i,item[i].name,item[i].code,item[i].qty,item[i].price,
                item[i].mfg.day,item[i].mfg.month,item[i].mfg.year);
    }

    fclose(fptr);
    getch();
    }
}

最佳答案

我认为您忘记了 for 循环:

        fprintf(fptr, "%d     %-15s        %-d          %-5d     %-5d     %d/%d/%d\n",i+1,item[i].name,item[i].code,item[i].qty,item[i].price,
                item[i].mfg.day,item[i].mfg.month,item[i].mfg.year);

尝试:

     for(i=0;i<n;i++)
     {
        fprintf(fptr, "%d     %-15s        %-d          %-5d     %-5d     %d/%d/%d\n",i+1,item[i].name,item[i].code,item[i].qty,item[i].price,
                item[i].mfg.day,item[i].mfg.month,item[i].mfg.year);
     }

此外,您正在以附加模式打开输出文件。我不确定你是有意这么做的。如果没有,请更改

fptr=(fopen("draftday.txt","a"));

fptr=(fopen("draftday.txt","w"));

关于C编程求助,如何使用C中的fopen和fprintf函数将给定的输出保存在文本文件中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27498560/

相关文章:

c - 如何在 C 中对 int* 指针使用 free 函数

c - 使用 sprintf 时出现循环错误

c - 在 C 中使用 va_arg() 时如何避免运行时错误

PHP MySQL 语句 - "select as"和 "where"

c - stat()、fstat()、lstat() 和 fopen();如何编写 TOCTOU protected 系统独立代码

c - Linux下可以设置本地时间的定时器吗?

c - 我想知道下面给定代码中的函数返回类型......并解释该代码是如何工作的?

C 程序在控制台上短暂显示,然后消失

具有多个句点的 C 文件名

php - 当大约 400 万条记录输入 MYSQL 时浏览器崩溃