Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 正在尝试写入文件_C_Fputs - Fatal编程技术网

C 正在尝试写入文件

C 正在尝试写入文件,c,fputs,C,Fputs,我正在尝试打开并写入.dat文件。该文件只是一个简单的数字系列,但我想添加到它。现在fputs对我不起作用 我想知道我是否使用了正确的功能来完成这项工作。现在,它说我不能使用整数在函数fputs中输入\u this,因为它不是一个常量字符 我想让用户向文件中添加一个整数。我理解这一点后的下一步是添加字符串、浮点、字符等。但是,仅仅是得到一些有用的东西是好的 #定义\u CRT\u安全\u无\u警告 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括 //functions calle

我正在尝试打开并写入.dat文件。该文件只是一个简单的数字系列,但我想添加到它。现在fputs对我不起作用

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

我想让用户向文件中添加一个整数。我理解这一点后的下一步是添加字符串、浮点、字符等。但是,仅仅是得到一些有用的东西是好的

#定义\u CRT\u安全\u无\u警告 #包括 #包括 #包括 #包括 #包括 #包括 #包括 #包括

//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
//调用的函数
//为什么它是空的?
内部主(空)
{
文件*pFile;
int-choice=0;
char-buf[40];
int i=0;
int num[40];
int输入此项;
printf(“欢迎使用。\n\n”);
pFile=fopen(“测试数据”,“r”);
if(pFile!=NULL)
对于(i=0;i<8;i++)
{
//获取num
fgets(buf、sizeof(buf)、pFile);
num[i]=atoi(buf);
printf(“#%i=%i\n”,i,num[i]);
}
printf(“输入要添加的编号:”);
获取_s(buf);
输入_this=atoi(buf);
FPUT(输入此,pFile);
fclose(pFile);
系统(“暂停”);
}//端干管
本例中的“void”表示函数“main”不接受任何参数。如果在C中只保留空参数,则表示函数接受可变数量的参数,而不是预期的0

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

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

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

if (!pFile) {
    puts("Something went wrong");
    exit(1);
}
最后,fputs接受一个字符串值,即字符常量。它将拒绝使用enter_this,因为它是一个整数。将整数写入文件的一种方法是使用。例如:

/* Write the integer enter_this & a newline to pFile */
fprintf(pFile, "%d\n", enter_this);

intfputs(constchar*str,FILE*stream)
那么这是否意味着我输入到文件中的所有内容都将被视为字符串?至少在我读取它并将其放入缓冲区并变为一个整数之前?这意味着您必须将一个指向字符串的
指针传递给fputs,您传递的是一个整数。如果要将数字写入文件,可以使用fprintf()或类似函数。如果要以读取模式“r”打开文件,那么如何在文件中写入?请在添加写入选项后尝试此操作,
fprintf(pFile,“%d”,输入此)
if (!pFile) {
    puts("Something went wrong");
    exit(1);
}
/* Write the integer enter_this & a newline to pFile */
fprintf(pFile, "%d\n", enter_this);