程序介绍:showbyte.c程序来源于哈工大《计算机系统》课程实验一,程序内容为以一行字符,一行对应的十进制整型的方式显示hello.c的内容
showbyte.c源代码:
#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
/*将文件内容读取到内存中*/
FILE *fp = NULL; // 文件指针
int file_long = 0; // 文件长度
char *read; // 内存指针(将文件内容读取到内存中)
int read_long; // 实际读取到的内存长度
fp = fopen("B:/code/C Primer Plus/test/hello.c", "r");// 打开文件,第一个参数为文件地址
if (fp == NULL)
{
printf("未获取到文件");
getchar();
return 0;
}
fseek(fp, 0, SEEK_END);
file_long = ftell(fp);
rewind(fp);
read = malloc(file_long + 1); // 末尾为\0
for (int i = 0; i < file_long + 1; i++) // 初始化内存
{
read[i] = 0;
}
fread(read, 1, file_long, fp);
fclose(fp);
read_long = strlen(read);
/*将内存内容打印出来*/
int sign = 0; // 标志,如果为0则打印内存中的字符,如果为1则打印十进制数
bool last_sign = true; // 是否未开始打印最后一行
for (int j = 0; j < read_long; j++)
{
if (j % 16 == 0 && j != 0 && last_sign == true) // 一行打印16个数
{
printf("\n");
if (sign == 0)
{
j = j - 16;
}
sign = !sign;
}
if (sign == 0)
{
if (read[j] == ' ')
printf(" sp "); // sp表示空格,如果不想要这种形式,可以把“ sp”换成“ ”
else if (read[j] == '\n')
printf(" \\n ");
else if (read[j] == '\t')
printf(" \\t ");
else
printf("%3c ", read[j]);
}
else if (sign == 1)
{
if (read[j] == ' ')
printf("%3d ", ' '); // 空格
else if (read[j] == '\n')
printf("%3d ", '\n');
else if (read[j] == '\t')
printf("%3d ", '\t');
else
printf("%3d ", read[j]);
}
if (j + 1 == read_long && last_sign && sign == 0)
{
printf("\n");
j = j - j % 16 - 1;
sign = !sign;
last_sign = false;
}
}
free(read);
getchar();// getchar会让程序等待击键,窗口会在用户按下一个键后才关闭
return 0;
}
程序输入(hello.c源代码)
#include <stdio.h>
int main()
{
printf("Hello World!\n");
getchar();
return 0;
}
程序输出
Windows下程序输出
Linux下程序输出
注意
- 代码中用到的函数的解释我都做成文档啦,需要的可以点击此处查看
- 代码中的文件路径需要更改为你的hello.c的文件路径(文件路径见fopen函数)
- fseek和ftell获取到的是文件占用的字节数,并不是文件中有效数据(所有字符)的字节数,即fseek获取到的是文件大小,而不是文件文本大小,文件大小比文件文本大小要大;而fread返回的是文件中有效数据的字节数,即文件文本大小,又因为文件文本由字符组成,一个字符占一字节,所以也可以说fread返回了文件中的字符数
- 大家copy的时候记得改一下变量名呐