簡體   English   中英

如何使用 fprintf 將緩沖區內容寫入/保存到 C 中的文件

[英]how to write/save a buffer content to a file in C using fprintf

我有一個 hidraw.c 代碼,我在下面使用“fprintf”將緩沖區內容寫入文件,但它不會將標准輸出寫入指定文件。 文件已創建,但文件為空。 有誰知道如何處理這個問題? 完整的源代碼可以在這里找到:

https://code.woboq.org/linux/linux/samples/hidraw/hid-example.c.html

下面是我需要幫助的代碼片段。 我是 C 編的新手。

FILE *fp;
int loop = 10;
fp=fopen("test.txt", "a");
while (loop !=0)
{
    res = read(fd, buf, 16);
    if (res < 0) {
        perror("read");
    } else {
        printf("read() read %d bytes:\n\t", res);
        
        if(fp == NULL)
                exit(-1);

        for (i = 0; i < res; i++)
            /* This printf will print buffer in the real time */
            /*printf("%hhx ", buf[i]);*/
            /* This is to write buffer to a file  but this does not capture the data*/  
            fprintf(fp, "%hhx ", buf[i]);
    }
}
fclose(fp);
close(fd); 

關於;

fprintf(fp, "%hhx ", buf[i]);

假設調用fopen()成功

這是將來自buf[]的字節放入 output stream 文件的 output 中。 但不將這些字節轉發到實際文件。

建議,循環完成后:

fflush( fp );

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM