[英]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. 我想学习如何在C语言中使用
getc
函数,因此编写了一个小程序,该程序应该将文本文件的首字母作为输出。 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
文件,我不知道为什么。 file.txt
is in the same folder as my program's .exe file. file.txt
与我的程序的.exe文件位于同一文件夹中。 I'm using Windows Vista. 我正在使用Windows Vista。 Thanks in advance
提前致谢
This extracts the program's location from argv[0]
这将从
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. 以便更好地了解错误原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.