0
 #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();
}

Thats what I got so far. Keep in mind that I tested this with a text file named "File". I just wrote "20" into it. I expected it to output the result of 20 + 10 (30) but it doesn't work.

Sandman
  • 17
  • 6
  • 2
    The `openfile` function just *prints* the contents of the file on the console. It doesn't actually *return* it as a value. – Some programmer dude Nov 02 '17 at 12:08
  • It should have been return c not return 0. But it still doesn't work... – Sandman Nov 02 '17 at 12:14
  • Hint: Use `c - '0'` to get the digit which was just read. – babon Nov 02 '17 at 12:14
  • I recommend learning more about [`fgetc`](http://en.cppreference.com/w/c/io/fgetc), and what its value might be after the loop finishes. I also recommend you read [How to debug small programs](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) by Eric Lippert, and learn how to step through your code line by line in a debugger while monitoring variables and their values. Lastly, you might want to take a few steps back, [get a good beginners book](http://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) and start over. – Some programmer dude Nov 02 '17 at 12:16
  • If your file just contains 20, the `c` variable is set 3 times in the while loop (because it reads only one character) then the loop breaks at `eof` and the last one is returned. In the the first iteration `c='2'`, than `c='0'` and the last value is `c=-1` (this is the `eof` contstant). This value is that what is returned. Better use `fscanf()` – Phil Fighter Nov 02 '17 at 12:40

1 Answers1

0

The openfile function always return 0 and just print content of the file on console. You should convert content of the file to number and return that value.

You can use:

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

Programmer dude
  • 167
  • 1
  • 5
  • 23