0
我是C新手,正在尝试完成一项任务。程序应该将文件名作为命令行参数,然后打印文件内容。我的程序打印文本混乱而不是文件中的实际文本。将文本文件中的字符添加到数组中
我已经在互联网上搜索了所有关于我的问题的示例/答案,并且仍然卡住!
我在做什么错?如果能够得到帮助,请修改我的代码,而不是编写新的代码,以便我能更轻松地理解。
int main()
{
char fileName[20];
int *buffer;
int size;
// ask for file name and take input.
printf("Enter file name: ");
scanf("%s", fileName);
// open file in read mode.
FILE *fp;
fp = fopen(fileName, "r");
// If no file, show error.
if(fp == NULL)
{
printf("Error: Can't open file.\n");
return 1;
}
// count characters in file with fseek and put into size, then move the
// position of the file back to the beginning.
fseek(fp, 0, SEEK_END);
size = ftell(fp);
rewind(fp);
// allocate buffer and read file into buffer.
buffer = malloc(size+1);
fread(buffer, 1, size, fp);
// close the file.
fclose(fp);
// for loop reading array one character at a time.
for(int x = 0; x < size; x++)
{
printf("%c", buffer[x]);
}
return 0;
}
始终保持缓冲区溢出的警惕。 20个字符的缓冲区非常小。如果编译代码时出现故障,*打开调试器*。 – tadman
'int * buffer' - >'char * buffer' –
'x
BLUEPIXY