在Linux系统中,可以使用以下方法将文本文件转换为二进制文件:
xxd -b <input.txt> <output.bin>
这将读取输入文本文件,并将其转换为二进制格式并保存为输出文件。
#include <stdio.h>
int main() {
FILE *inputFile = fopen("input.txt", "r");
FILE *outputFile = fopen("output.bin", "wb");
if (inputFile == NULL || outputFile == NULL) {
printf("Failed to open file.\n");
return 1;
}
char c;
while ((c = fgetc(inputFile)) != EOF) {
fwrite(&c, sizeof(char), 1, outputFile);
}
fclose(inputFile);
fclose(outputFile);
return 0;
}
with open("input.txt", "r") as inputFile:
with open("output.bin", "wb") as outputFile:
for line in inputFile:
outputFile.write(line.encode())
这些方法将文本文件的内容逐字节转换为二进制,并保存为二进制文件。