Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading