我正在尝试使用fprintf将程序写入文本文件。
问题
当我使用fprintf(stdout,"%x",pbtData[szPos]);
时,它将成功打印出12345678.但是当我使用fprintf(f,"%x",pbtData[szPos]);
写入文件时,它只会写入最后两位数78,为什么会这样?当我使用stdout?
fprintf part
static void
print_hex(const uint8_t *pbtData ,const size_t szBytes)
{
size_t szPos;
for (szPos = 0; szPos < szBytes; szPos++) {
// printf("%x",pbtData[szPos]);
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fprintf(f,"%x",pbtData[szPos]);
fclose(f);
}
printf("\n");
}
完整代码
#include <stdlib.h>
#include <nfc/nfc.h>
static void
print_hex(const uint8_t *pbtData ,const size_t szBytes)
{
size_t szPos;
for (szPos = 0; szPos < szBytes; szPos++) {
// printf("%x",pbtData[szPos]);
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
fprintf(f,"%x",pbtData[szPos]);
fclose(f);
}
printf("\n");
}
int
main(int argc, const char *argv[])
{
nfc_device *pnd;
nfc_target nt;
// Allocate only a pointer to nfc_context
nfc_context *context;
// Initialize libnfc and set the nfc_context
nfc_init(&context);
if (context == NULL) {
printf("Unable to init libnfc (malloc)\n");
exit(EXIT_FAILURE);
}
// Display libnfc version
const char *acLibnfcVersion = nfc_version();
(void)argc;
printf("%s uses libnfc %s\n", argv[0], acLibnfcVersion);
// Open, using the first available NFC device which can be in order of selection:
// - default device specified using environment variable or
// - first specified device in libnfc.conf (/etc/nfc) or
// - first specified device in device-configuration directory (/etc/nfc/devices.d) or
// - first auto-detected (if feature is not disabled in libnfc.conf) device
pnd = nfc_open(context, NULL);
if (pnd == NULL) {
printf("ERROR: %s\n", "Unable to open NFC device.");
exit(EXIT_FAILURE);
}
// Set opened NFC device to initiator mode
if (nfc_initiator_init(pnd) < 0) {
nfc_perror(pnd, "nfc_initiator_init");
exit(EXIT_FAILURE);
}
printf("NFC reader: %s opened\n", nfc_device_get_name(pnd));
// Poll for a ISO14443A (MIFARE) tag
const nfc_modulation nmMifare = {
.nmt = NMT_ISO14443A,
.nbr = NBR_106,
};
if (nfc_initiator_select_passive_target(pnd, nmMifare, NULL, 0, &nt) > 0) {
print_hex(nt.nti.nai.abtUid,nt.nti.nai.szUidLen);
}
// Close NFC device
nfc_close(pnd);
// Release the context
nfc_exit(context);
exit(EXIT_SUCCESS);
}
答案 0 :(得分:1)
您需要将文件的打开/关闭移出循环。
FILE *f = fopen("file.txt", "w");
if (f == NULL)
{
printf("Error opening file!\n");
exit(1);
}
for (szPos = 0; szPos < szBytes; szPos++) {
// printf("%x",pbtData[szPos]);
fprintf(f,"%x",pbtData[szPos]);
}
printf("\n");
fclose(f);
您可能需要在输出中添加空格以清楚地看到输出。
fprintf(f, "%x ", pbtData[szPos]);
// ^