简体   繁体   中英

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

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;
}

Try

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

for a better understanding of the cause of error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM