简体   繁体   中英

Can't read data from text file written by c program

I am trying to write the number of packets I get to a textfile:

printf("TCP : %d   UDP : %d   ICMP : %d   IGMP : %d   Others : %d   Total : %d\r", tcp , udp , icmp , igmp , others , total);
if (usePacketCount == 1){
    fprintf(stderr,"Saving packet count");
    fprintf(packetCountFile,"TCP : %d   UDP : %d   ICMP : %d   IGMP : %d   Others : %d   Total : %d\r", tcp , udp , icmp , igmp , others , total);
}

When I run the program, I clearly get to this point in the code: 在此处输入图像描述

However when I try to read the textfile, there is nothing present:

在此处输入图像描述

I define my file here:

FILE *packetCountFile = 0;

if (usePacketCount == 1){
    printf("Using Packet Count File");
    packetCountFile = fopen("packetCount.txt","w");
}

I am not sure why this is failing. It may be due to the write being in a loop, and it simply can't keep up?

First, always check the return values of fopen and fprintf for failure. Second, the text editor shows 0 lines and 898964 characters. This is something.

What happened?

The format string given to fprintf ends with a carriage return character ( \r ), which causes fprintf to write and repeatedly overwrite the first line.

Okay, but why doesn't that first line appear in the text editor?

This depends on the system and text editor, but what probably happens is that the text editor displays lines of text. POSIX defines a line as follows

A sequence of zero or more non-<newline> characters plus a terminating <newline> character.

Since fprintf did not print a newline character, the file technically did not contain a single line.
Some text editors are more lenient with this than others and may actually show some contents.

Your question: "It may be due to the write being in a loop, and it simply can't keep up?"

If the system couldn't keep up, you'd expect fprintf to fail or for the writing to be slow.

How do I solve this?

Replace the carriage return character ( \r ) with a newline character ( \n ), which is probably what you meant to write in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM