我试图通过试验和测试来了解指针与字符串之间的关系,我尝试运行该程序,但是当我输入文件时,它并没有出错,但已得到遵守
char *file_name;
printf("Enter the name of the file:");
gets(file_name);
printf("the file name is: %s",file_name);
我试图通过试验和测试来了解指针与字符串之间的关系,我尝试运行该程序,但是当我输入文件时,它并没有出错,但已得到遵守
char *file_name;
printf("Enter the name of the file:");
gets(file_name);
printf("the file name is: %s",file_name);
指针
char *file_name;
未初始化,并且具有不确定的值。所以下面的语句
gets(file_name);
调用未定义的行为。
此外,函数gets
不是标准的C函数,因此不安全。
您需要做的是在要读取文件名的地方分配一个内存,并使用标准的C函数fgets
而不是gets。
例如
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//…
size_t n = 100;
char *file_name = malloc( n );
fgets( file_name,n,stdin );
file_name[ strcspn( file_name,"\n" ) ] = '\0';
printf("the file name is: %s\n",file_name);
//…
free( file_name );
//...
此声明
file_name[ strcspn( file_name,"\n" ) ] = '\0';
需要排除可以由功能'\n'
附加到输入字符串的换行符fgets
。