课堂练习2
一、xxd的使用
二、
xxd的主要功能是将文件转化为十六进制显示,通过man xxd可以得到,需要使用unistd.h实现
三、伪代码
openfile
readbyte
0x
new text
print 0x
四、
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void print_hex_dump(FILE *file, long offset, int length) {
fseek(file, offset, SEEK_SET);
unsigned char buffer[length];
size_t bytesRead = fread(buffer, 1, length, file);
if (bytesRead == 0) {
printf("Error reading file.\n");
return;
}
printf("File Length: %ld bytes\n", bytesRead);
for (size_t i = 0; i < bytesRead; i++) {
printf("%02X ", buffer[i]);
}
printf("\n");
}
int main(int argc, char *argv[]) {
if (argc != 4) {
printf("Usage: %s <option> <n> <filename>\n", argv[0]);
printf("Options:\n");
printf(" -h n Display the first n bytes of the file.\n");
printf(" -t n Display the last n bytes of the file.\n");
return 1;
}
int n = atoi(argv[2]);
if (n <= 0) {
printf("Invalid value for n. Please provide a positive integer.\n");
return 1;
}
char *filename = argv[3];
FILE *file = fopen(filename, "rb");
if (!file) {
printf("Error opening file: %s\n", filename);
return 1;
}
if (strcmp(argv[1], "-h") == 0) {
print_hex_dump(file, 0, n);
} else if (strcmp(argv[1], "-t") == 0) {
fseek(file, 0, SEEK_END);
long fileLength = ftell(file);
long offset = (fileLength - n) >= 0 ? (fileLength - n) : 0;
print_hex_dump(file, offset, n);
} else {
printf("Invalid option: %s\n", argv[1]);
fclose(file);
return 1;
}
fclose(file);
return 0;
}