how to read lines in C code example

Example 1: how to count lines in a file c

/* C Program to count the Number of Lines in a Text File  */
#include <stdio.h> 
#define MAX_FILE_NAME 100 
  
int main() 
{ 
    FILE *fp; 
    int count = 0;  // Line counter (result) 
    char filename[MAX_FILE_NAME]; 
    char c;  // To store a character read from file 
  
    // Get file name from user. The file should be 
    // either in current folder or complete path should be provided 
    printf("Enter file name: "); 
    scanf("%s", filename); 
  
    // Open the file 
    fp = fopen(filename, "r"); 
  
    // Check if file exists 
    if (fp == NULL) 
    { 
        printf("Could not open file %s", filename); 
        return 0; 
    } 
  
    // Extract characters from file and store in character c 
    for (c = getc(fp); c != EOF; c = getc(fp)) 
        if (c == '\n') // Increment count if this character is newline 
            count = count + 1; 
  
    // Close the file 
    fclose(fp); 
    printf("The file %s has %d lines\n ", filename, count); 
  
    return 0; 
}

Example 2: c read lines from text file in to array

FILE *fp;        // pointer to file
    char *file_name; // file path
    char cur_char;
    char *line = NULL; // line array
    size_t len = 0;
    ssize_t read;
    int counter = 0;

    //char content[MAX_NUM_LINES][MAX_LINE_LENGTH];
    char strArray[150][150];
    if (optarg == 0)
    {
        printf("File could not be opened.");
        return;
    }
    // has file argument
    fp = fopen(optarg, "r");

    if (fp != NULL)
    {

        while ((read = getline(&line, &len, fp)) != -1) // loop thru lines and add them to the strArray
        {
            // fgets(line, 100, fp);
            int i = 0;
            while(line[i] != '\n'){ // loop thru the characters in the current line
                strArray[counter][i] = line[i];
                i++;
            }
            
            counter++;//counts the number of lines in the file
         
        }
        }

Tags:

C Example