简体   繁体   中英

Reading data from a file with C

I am trying to read data from a file with C.

This is how the file (text.txt) looks like:

element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7
element1 element2 element3 element4 element5 element6 element7

Below you see my code:

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

void read_txt(){
    FILE *fp;
    char buf[100];
    size_t bytes_read;

    fp = fopen("text.txt", "a");

    if (fp == NULL) {
        printf("File couldn't be opened properly.");
        exit(1);
    }

    bytes_read = fread(buf, sizeof(buf), 1, fp);

    printf("%zu\n", bytes_read);
    printf("%s\n", buf);

    fclose(fp);
}


int main(void)
{
    read_txt();
    return 0;
}

Unfortunately, all I get is the following:

0
h
Program ended with exit code: 0

What is the correct way to use fread in order to achieve my objective which is read and print all the data in my file?

Your use of fread looks all right. However, you should open your file with "r" rather than "a" . When you open the file with "a" the stream is positioned at the end of the file instead of the beginning. Of course you then have to read your file in a loop because your file contains more than 100 characters

fp = fopen("text.txt", "a");
change to
fp = fopen("text.txt", "r");

RETURN VALUE On success, fread() and fwrite() return the number of items read or written. This number equals the number of bytes transferred only when size is 1. If an error occurs, or the end of the file is reached, the return value is a short item count (or zero).

I don't know if there's a FAQ I should be pointing you to, but this question comes up often and the solution almost always has the form:

static const int M = 3; // For example.
int nread = -1;
int a = -1, b = -1, c = -1;

while ( M == ( nread = scanf( "%d %d %d", &a, &b, &c ) ) )
  do_stuff_with( a, b, c );

// Check why the last call failed.
// Was it due to feof(stdin) with 0 == nread, or did something go wrong?

When it doesn't, the right thing to do is usually to read a block in binary format with

sometype buffer[M];
while ( M == fread( buffer, sizeof(sometype), M, stdin ) )
  do_stuff_with( M, buffer );

Note that you were reversing the size and count arguments to fread() , although it will probably still work.

Sometimes, what people want to do is read a line with fgets() ( not gets() !) and parse it with sscanf() .

Stuff too complicated for that probably calls for a regex library or parser.

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