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

时间:2017-11-02 12:06:14

标签: 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();
}

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

1 个答案:

答案 0 :(得分:0)

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

您可以使用:

int c; fscanf(file, "%d", &c); return c;