在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())
這些方法將文本文件的內容逐字節轉換為二進制,并保存為二進制文件。