简体   繁体   中英

Reading file, line by line, character by character in C

I have a problem with reading a file in C.
I want to read a file line by line.
Each line contains 25 characters and each character has a special value that I have to use in other functions. My code:

int read_file(const char* filename){

    FILE* file = fopen(filename, "r");
    char line[25];
    int i;
    int counter = 0;



    while (fgets(line, sizeof(line), file))
    {
        if (counter == 0)
        {
            counter++;
        }
        else
        {

                for(i = 0; i < 25 ; i++){
                     printf("%s",line[i]);
                }
        }
    }

    fclose(file);

    return 0;
}

I have to do something else then print it, but when I try this code, it gives errors, so doing something else would do the same I guess. So my code needs to read the file line by line and then I need to be able to read it character by character.

  • An array of 25 elements isn't enough to store lines of 25 characters: +1 for newline and +1 for terminating null character.
  • You should check if the opening of the file is successful
  • %c have to be used to print one character via printf .

fixed code:

#include <stdio.h>

int read_file(const char* filename){

    FILE* file = fopen(filename, "r");
    char line[27]; /* an array of 25 elements isn't enough to store lines of 25 characters: +1 for newline and +1 for terminating null character */
    int i;
    int counter = 0;

    if (file == NULL) return 1; /* check if the file is successfully opened */

    while (fgets(line, sizeof(line), file))
    {
        if (counter == 0)
        {
            counter++;
        }
        else
        {

            for(i = 0; i < 25 ; i++){
                 printf("%c",line[i]); /* use %c instead of %s to print one character */
            }
        }
    }

    fclose(file);

    return 0;
}
 printf("%s",line[i]);     // %s expects char * and line[i] is  a char 

This should be -

 printf("%c",line[i]);     // to print character by charcter 

To store 25 characters declare line as -

char line[25+1];  // +1 for null character

Note - As you ask in comment to %s can be used as -

printf("%s",line);         // no loop required

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