c - getc 和 fgetc 不起作用...给出分段错误
问题描述
我正在尝试将一个文件的内容复制到另一个文件中。在我完成之前,我想在屏幕上打印内容以查看一切是否正常。但他们没有。
包括我...
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
我的代码是...
void decodeBin(char * filename){
//opens filename for reading and outfilename for writing
FILE * input = fopen(filename, "r");
char file_name[] = "";
strcpy(file_name, filename);
char out_file[] = "out";
strcat(out_file, file_name);
FILE * output = fopen(out_file, "w");
char ch;
if (input != NULL){
while((ch = fgetc(input)) != EOF)
printf("%c", ch);
}
fclose(input);
fclose(output);
}
我查看了其他堆栈溢出帖子,其中建议检查文件指针是否不为空,我这样做了。怎么了?
解决方案
通过在file_name
andout_file
数组的范围之外写入会导致未定义的行为。当您没有为数组指定大小时,大小由您用来初始化它的字符串确定。所以它相当于
char file_name[1] = "";
char out_file[4] = "out";
额外的字节用于尾随的空值。
由于您没有为要复制到其中的字符串声明足够大的数组,因此您会得到未定义的行为。
您需要声明数组的大小足以容纳最大可能的文件名。或者malloc()
根据参数来调整它的大小。
不需要file_name
变量,因为它只是 的副本filename
,您可以直接使用它。
char *outfile = malloc(strlen(filename) + sizeof("out"));
sprintf(outfile, "out%s", filename);
然后在函数结束时,执行
free(outfile);
推荐阅读
- php - Wordpress - wp_handle_upload - how to get the file name/directory of the uploaded file?
- scala - Where is the inverse reduce optimization in the Dataset/Dataframe API in Spark Structured Streaming 2.3.0
- javascript - Twilio JWT 令牌已过期
- sql - Equal to Not equal in or clause of where
- php - PHP Composer working in locally but not in root user (centos 7)
- sql-server - CASE 语句 - 将数据类型 nvarchar 转换为数字时出错
- python - 将列表附加到字典值时出现键错误
- python-2.7 - BigQuery - create an external table in Python
- logging - Rails 的哪个记录器提供控制器名称、服务名称
- amazon-web-services - 我可以将托管在 EC2 中的其余服务用作 SNS HTTP 订阅吗?