C 以指向字符串的指针作为名称读取文件
C read file with pointer to string as name
我有一个虚拟函数 char * getFileName() 只是 returns 一个指向字符数组的指针:
char * getFileName () {
char buff[11] = "index.html";
char *p;
p = buff;
printf ("name of the file: %s\n", p);
return p;
}
在我的例子中,这个指针是 name 是我要打开并从 main 读取的文件的名称:
int main() {
char *fp;
FILE *file;
fp = getFileName();
int c;
file = fopen(fp, "r");
if (file) {
while ((c = getc(file)) != EOF) {
putchar(c);
}
fclose(file);
}
return (0);
}
但是,我无法使用指针值作为名称打开该文件,尽管当我打印 fp 时,我得到了正确的文件名称:index.html。有什么建议我可能会遗漏吗?谢谢:)
您正在返回一个指向局部变量的指针 - 当 getFileName()
returns、buff
被销毁并且 p
的值指向内存时不再可用。
如果你真的想这样做,你必须使 buff
成为一个 static
变量:
char *getFileName(void) {
static char buff[] = "index.html";
char *p;
p = buff;
printf ("name of the file: %s\n", p);
return p;
}
static
变量不是堆栈分配的;它们是..好吧..静态分配的。
其他一些重要细节:
- 不接收任何参数的函数
f
应声明为 f(void)
。
- 在这种情况下,您不必显式写出
buff
的大小,因为您使用 "index.html"
. 初始化了它
我有一个虚拟函数 char * getFileName() 只是 returns 一个指向字符数组的指针:
char * getFileName () {
char buff[11] = "index.html";
char *p;
p = buff;
printf ("name of the file: %s\n", p);
return p;
}
在我的例子中,这个指针是 name 是我要打开并从 main 读取的文件的名称:
int main() {
char *fp;
FILE *file;
fp = getFileName();
int c;
file = fopen(fp, "r");
if (file) {
while ((c = getc(file)) != EOF) {
putchar(c);
}
fclose(file);
}
return (0);
}
但是,我无法使用指针值作为名称打开该文件,尽管当我打印 fp 时,我得到了正确的文件名称:index.html。有什么建议我可能会遗漏吗?谢谢:)
您正在返回一个指向局部变量的指针 - 当 getFileName()
returns、buff
被销毁并且 p
的值指向内存时不再可用。
如果你真的想这样做,你必须使 buff
成为一个 static
变量:
char *getFileName(void) {
static char buff[] = "index.html";
char *p;
p = buff;
printf ("name of the file: %s\n", p);
return p;
}
static
变量不是堆栈分配的;它们是..好吧..静态分配的。
其他一些重要细节:
- 不接收任何参数的函数
f
应声明为f(void)
。 - 在这种情况下,您不必显式写出
buff
的大小,因为您使用"index.html"
. 初始化了它