AdamTomaszA
AdamTomaszA

Reputation: 11

C. Can't open a text file with fopen on Windows Vista

I wanted to learn how to use getc function in C so I wrote a little program that is supposed to give the first letter of a text file as an output. Here's how it looks:

int main()
{
    int character;
    FILE *file;
    file = fopen("file.txt", "r");
    if(file == NULL)
        printf("can't open\n");
    character = getc(file);
    printf("%c", character);
    fclose(file);
    return 0;
}

It fails to open the file.txt file and I can't figure out why. file.txt is in the same folder as my program's .exe file. I'm using Windows Vista. Thanks in advance

Upvotes: 1

Views: 81

Answers (2)

pmg
pmg

Reputation: 108978

Try

if (plik == NULL) { perror("plik.txt"); exit(EXIT_FAILURE); }

for a better understanding of the cause of error.

Upvotes: 1

Weather Vane
Weather Vane

Reputation: 34575

This extracts the program's location from argv[0]

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MYFILE "plik.txt"

int main(int argc, char *argv[]) {
    char fname[_MAX_PATH+1];
    int znak;
    FILE *plik;
    char *ptr;
    strcpy(fname, argv[0]);
    ptr = strrchr(fname, '\\');
    if(ptr == NULL) {
        strcpy(fname, MYFILE);
    }
    else {
        strcpy(ptr+1, MYFILE);
    }
    plik = fopen(fname, "r");
    if(plik == NULL) {
        printf("Can't open %s\n", fname);
    }
    else {
        znak = getc(plik);
        printf("First char of %s is %c\n", fname, znak);
        fclose(plik);
    }
    getchar();
    return 0;
}

Upvotes: 1

Related Questions