cgccinputtextgetc

C Programming , getc() , stdin , file redirection


My assignment is to redirect a text file and do all sorts of operations on it , everything is working except I have a little problem :

so the main function that reads input is getline1():

char* getline1(){
char *LinePtr = (char*)malloc(sizeof(char*)*LINE);
int i = 0;
for ( ; (*(LinePtr+i) = getc(stdin)) != '\n' ; i++){}
*(LinePtr+i) = '\0';
return LinePtr;
}

it returns a pointer to char array of a single line,

so we know that a new line saparates with '\n' char,

previous problem I had is when I wrote the getline1() function like this :

for (int i = 0 ; Line[i] != '\n' ; i++){
Line[i] = getc(stdin);
}

as it logically it may be authentic the getc() is a streaming function and I saw online answers that this will not work didn't quite understand why.

anyway the big issue is that I need to know how many lines there are in the text so I can stop reading values , or to know from getline1() function that there is no next line left and Im done.

things we need to take for account : 1.only <stdio.h> <stdlib.h> need to be used 2.Im using Linux Ubuntu and gcc compiler 3.the ridirection goes like ./Run<input.txt

also I understand that stdin is a file pointer , didn't found a way that this can help me.

Thank you , Denis


Solution

  • You should check for the EOF signal in addition to the newline character, you should also check for that your index-1 is always smaller than LINE to avoid overflow and also save space for the NULL terminator.

    #define LINE 100
    
    char *my_getline(void)
    {
        size_t i = 0;
        char *str = NULL;
        int c = 0;
    
         if ((str = malloc(LINE)) == NULL)
         {
             fprintf(stderr,"Malloc failed");
             exit(EXIT_FAILURE);
         }
    
        while (i+1 < LINE && (c = getchar()) != EOF && c != '\n') /* Saving space for \0 */
        {
            str[i++] = c;
        }
        str[i] = '\0';
    
        return str;
    }