简体   繁体   中英

How to read text file in C?

I'm trying to read a txt file containing strings of 1s and 0s and print it out in the manner below. I tried my code a couple of months ago and it worked fine in reading the text file. Now when I tried it, it outputs something really strange. Also I tried changing the directory of the file to a non-existant file but it still outputs the same thing when it should've quit the program immediately. Please help!

The content of txt file:-

10000001
01110111
01111111
01111010
01111010
01110111

Expected output:-

data_in<=24'b10000001;
#10000;

Real output:-

data_in<=24'b(some weird symbol that changes everytime I recompile);
#10000;

My code:-

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[])
{
    int i, j;
    j = 0;
    char words[50];
    FILE *fp;
    fp = fopen (argv[1], "r");

    if (fp == NULL) {
        printf ("Can't open file\n");
    }

    while (feof (fp) == 0) {
        fscanf (fp, "%s", words);
        printf ("data_in<=24'b%s\n", words);
        printf ("#10000\n");
    }

    fclose (fp);
    system ("PAUSE");
    return 0;
}

The input argument is the following:-

"C:\Users\Beanz\Documents\MATLAB\football frame\frame1.txt"

使用getline(3) -如果可用-或使用fgets逐一读取每一行(然后您将需要足够大的行缓冲区,至少256个字节),然后使用sscanf适当地解析每个行缓冲区( %n可能有用,您应该测试sscanf或其他功能(例如strtokstrtol等)的扫描项目计数结果

Remember that 'feof()' is only set AFTER trying to read PAST the end of the file, not when at the end of the file.

So the final iteration through the loop will try to read/process data that contains trash or prior contents.

Always check the returned value from 'fscanf()' before trying to use the associated data.

strongly suggest

eliminate the call to feof() and use the fscanf() to control the loop

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