-2

At first I wanted to open a file and read its contents, in C, however, in doing so, I was unable to run the program without errors, I even tried to just open the file, and not read anything, I did exactly what I saw on other questions like this and got errors, here is the code.

#include <stdio.h>
void main(void){
        FILE *file = NULL;
        file = fopen('list.txt', 'r');
        }
J. Doe
  • 53
  • 3
  • 7
  • 5
    You should include the error(s) you got when you ran this code. One of them was probably '`main` should return `int` and not `void`' – Arc676 Jun 18 '17 at 01:23
  • 2
    `void main` is bad. Also you state you get errors so why dont you tell us what the errors are – TheQAGuy Jun 18 '17 at 01:23
  • The prototype for `main()` in C is `int main(int argc, char *argv[])` – twain249 Jun 18 '17 at 01:23
  • 1
    Possible duplicate of [In C, how should I read a text file and print all strings](https://stackoverflow.com/questions/3463426/in-c-how-should-i-read-a-text-file-and-print-all-strings) – Stargateur Jun 18 '17 at 01:25
  • 4
    `fopen('list.txt', 'r')` --> `fopen("list.txt", "r")` – BLUEPIXY Jun 18 '17 at 01:27
  • 1
    Always **always** validate the return of `fopen`, e.g. `FILE *fp = NULL; if (fopen ("path/to/myfile", "r") == NULL) {...handle error...}` and since `main` takes arguments, *use them* to avoid hardcoding filenames, e.g. `int main (int argc, char **argv) { FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin; if (!fp) {...handle error...}...` to open the filename passed as the first argument (or read from `stdin` if no filename is provided). – David C. Rankin Jun 18 '17 at 03:29
  • `void main`? I think you meant `int main`! – autistic Jun 18 '17 at 03:41
  • Why do tutorials sometimes say `void main()`? – Mateen Ulhaq Jun 18 '17 at 03:51

2 Answers2

3

(Repeating BLUEPIXY's comment as an answer so search finds it)

Your mistake is that in 'list.txt', 'r' the ' does not mark a string in 'C' (unlike in python) you must use ".

The ' is used to specify `a single character variable.

Martin Beckett
  • 94,801
  • 28
  • 188
  • 263
1

First of all do you have a file called list.txt, and what if the program does not find list.txt. It can't read the file so you must check for exist file.

#include <stdio.h>
int main (void) {
    FILE *file_exist = fopen("list.txt", "r");
    if (file_exist) {
        printf("File Founded");
        //Insert what do you want to do with the file like fscanf? fgetc? Up to you
    }
    else {
        printf("File Not Found");
        //If there is no file, You can start ignore reading the file since will cause error dont know what to read
    }
}

Here you can avoid error, while reading your file.