-1

我正在尝试打开然后写入 .dat 文件。该文件只是一系列简单的数字,但我想添加它。现在 fputs 不适合我。

我想知道我是否使用正确的功能来完成这项工作。现在它说我不能 在函数fputs中使用整数enter_this因为它不是一个常量字符。

我想要求用户在文件中添加一个整数。了解这一点后,我的下一步是添加字符串、浮点数、字符等。但只要得到一些有效的东西就很好。

#define _CRT_SECURE_NO_WARNINGS #include #include #include #include #include #include #include #include

//functions called

//why is it void?
int main(void)
{

    FILE *pFile;
    int choice = 0;
    char buf[40];
    int i = 0;
    int num[40];
    int enter_this;

    printf("WELCOME. \n\n");
    pFile = fopen("test.dat", "r");
    if (pFile != NULL)

    for (i = 0; i < 8; i++)
    {
        //get num
        fgets(buf, sizeof(buf), pFile);
        num[i] = atoi(buf);

        printf("#%i = %i\n", i, num[i]);
    }


    printf("Enter number to be added: ");
    gets_s(buf);
    enter_this = atoi(buf);
    fputs(enter_this, pFile);
    fclose(pFile);

    system("pause");

}//end main
4

1 回答 1

1
int main(void)

在这种情况下,“void”意味着函数“main”不接受任何参数。如果你只在 C 中留下空括号,这意味着该函数接受可变数量的参数,而不是你可能期望的 0。

如果要在文件末尾添加数字,则必须以“附加模式”打开它:

FILE *pFile = fopen("test.dat", "a");

第二个参数“a”是一个模式字符串。它告诉 fopen 打开文件进行追加,即数据将写入文件末尾。如果文件不存在,则创建它。您当前正在以“只读”模式打开文件,并且根本无法写入。在此处阅读 fopen 采用的不同模式字符串。

检查文件指针是否为 NULL 也是多余的。当指针不为 NULL 时,您没有将任何块传递给“if”以运行。它应该是这样的:

if (!pFile) {
    puts("Something went wrong");
    exit(1);
}

最后,fputs 接受一个 STRING 值,即一个字符常量。它将拒绝与 enter_this 一起使用,因为它是一个整数。将整数写入文件的一种方法是使用fprintf。例如:

/* Write the integer enter_this & a newline to pFile */
fprintf(pFile, "%d\n", enter_this);
于 2014-03-25T04:34:14.700 回答