#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/