我在CppCheck中得到上述错误,但我看不出出了什么问题。我想错误是我的代码找不到任何文件的原因,即使它们存在于我的计算机中。如有任何帮助,不胜感激。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIZE 80
char *getchoice(void);
void getfile(char *filename);
int main() {
char *choice;
choice=getchoice();
getfile(choice);
return 0;
}
char *getchoice(void) {
char *filename;
filename=malloc(SIZE);
printf("Enter the name of the text file: ");
scanf("%30s",filename);
return filename;
}
void getfile(char *filename) {
FILE *fp;
fp=fopen(filename,"r");
if (fp==NULL){
printf("The entered file does not exist.");
printf("n");
}
else{
printf("The file exists.");
}
fclose(fp);
return;
}
为了清理这个程序,下面列出了要做的事情:
- 处理
malloc
故障,导致scanf
和getfile
不通过NULL
。 - 检查
scanf
是否成功执行了预期的转换次数,以确保filename
包含有效的数据。 - 使用
perror
给出malloc
或fopen
失败的更准确的信息。 - 避免将
NULL
传递给fclose
,以防fopen
失败。 free
内存由malloc
分配(不像fclose
,free
可以安全地通过NULL
)。
#include <stdio.h>
#include <stdlib.h>
char *getchoice(void);
void getfile(char *filename);
int main(void) {
char *choice = getchoice();
if (choice)
getfile(choice);
free(choice);
}
char *getchoice(void) {
char *filename = malloc(80);
if (filename) {
printf("Enter the name of the text file: ");
if (1 != scanf("%79s", filename)) {
free(filename);
return NULL;
}
} else {
perror("malloc");
}
return filename;
}
void getfile(char *filename) {
FILE *fp = fopen(filename, "r");
if (fp) {
puts("File opened.");
fclose(fp);
} else {
perror("fopen");
}
}