c - 如何将文件中保存的值添加到另一个变量?

标签 c

 #include <stdio.h>

int openfile () //opens a file and saves the content in c
{
    int c;
    FILE *file;

    file = fopen("File", "r"); /* looks for a File named "File" */
    if (file == NULL) 
    {
        printf("Error\n");
    }

while(1) {
    c = fgetc(file);
    if(feof(file)) { 
        break;
        }
    printf("%c", c); /* This prints the contents of the file */
    }
fclose(file);
return c;
}

int otherfunction1337() /* <- Problem: Why doesn't this add 10 and the
content of the file (in my example I wrote 20 into the file) */
{
int a = 10 + openfile(); /* ? */
printf("%i", a);
return 0;
}

int main (void)
{
otherfunction1337();
}

这就是我到目前为止所得到的。请记住,我使用名为“File”的文本文件对此进行了测试。我刚刚在其中写了“20”。我期望它输出 20 + 10 (30) 的结果,但它不起作用。

最佳答案

openfile 函数始终返回 0,并且仅在控制台上打印文件内容。您应该将文件的内容转换为数字并返回该值。

您可以使用:

int c; fscanf(文件, "%d", &c); 返回c;

关于c - 如何将文件中保存的值添加到另一个变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47074883/

相关文章:

c - 什么是 Rss 信息?不是 Rss xml 提要

c - 无法从 Linux 计算机将 UDP 发送到多播组

c - 让我的 C 代码更短

c - 如何将数组分配给C中的结构

C - 为什么将结构放在 union 中?

C-SYSMALLOC : Assertion failed (realloc)

c - 如何将 C_FLOAT 数组传递给 Fortran 子例程

c - 如何创建函数,在 C 中没有 typedef 的情况下返回指向另一个函数的指针?

c - 这段代码里有UB吗?

c - rand() 函数每次产生相同的输出 C