cfilewhile-loopeoffgetc

VS Code. File contents are not displayed in TERMINAL and OUTPUT


I'm using VSCode on Ubuntu 24.04.01.The screenshot shows a program that reads and displays the contents of a file. The "my_file.txt" contains the word "Hello". When I run the code on the TERMINAL and OUTPUT there is no "Hello" message. How can I print the word "Hello" on the TERMINAL and OUTPUT? Thanks for the answer

#include<stdio.h>

int main()
{
   
    char buff[100];
  
   FILE *in = fopen("my_file.txt", "r");
    if(in == NULL)
       return 2;

    char ch;
    int i = 0;
    while(ch = fgetc(in) != EOF)
       buff[i++] = ch;
    buff[i] = '\0';
  
    puts(buff);  
        
    fclose(in);
    
    return 0;
}

I tried searching in the settings and in the file task.json...


Solution

  • There are at least three drawbacks in your program.

    The first one is that the variable ch should be declared as having type int. Otherwise the result of such a condition like ch == EOF or ch != EOF is implementation defined.

    The second drawback is that the condition in this while loop

    while(ch = fgetc(in) != EOF)
    

    is equivalent to

    while( ch = ( fgetc(in) != EOF ) )
    

    due to the operator precedence and as a result the variable ch will be set either to 1 or 0.

    You need to write at least like

    while (  ( ch = fgetc( in ) ) != EOF )
    

    And the third drawback is that you should guarantee that the array buff will not be overwritten. So you need to write for example

    #include <stdio.h>
    
    int main( void )
    {
        enum { N = 100 };
        char buff[N];
      
        FILE *in = fopen( "my_file.txt", "r" );
        
        if ( in == NULL ) return 2;
    
        int ch;
        int i = 0;
      
        while ( i < N - 1 && ( ch = fgetc( in ) ) != EOF )
        {
            buff[i++] = ch;
        }
    
        buff[i] = '\0';
      
        puts( buff );  
            
        fclose( in );
        
        return 0;
    }
    

    Also you should be sure that the file indeed exists in the working directory. You could write for example

    if ( in == NULL ) 
    {
        puts( "File not found." );
        return 2;
    }