-1

Im new to C programming and Im trying to make a program that reads the context of a file named input.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char ch;
    FILE *in;
    in = fopen("input","r");
    printf("The contents of the file are\n");
    fscanf(in,"%c",&ch);
    printf("%c",ch);
    fclose(in);
    return 0;
}
REALFREE
  • 4,378
  • 7
  • 40
  • 73
Eric Z
  • 21
  • 1

4 Answers4

1

Your code is reading just the first character of the file. There is no loop to read over the complete file. Is that what you intended?

Also, check if the file open was successful. Is the input file name "input" ?

lamirap
  • 510
  • 1
  • 3
  • 8
0

Try this -

char text[100];
fp=fopen(name,"r");
fgets(text,sizeof(text),fp); //99 is maximum number of characters to be printed including newline, if it exists
printf("%s\n",text);
fclose(fp);
Riken Shah
  • 3,022
  • 5
  • 29
  • 56
  • 1
    "100 is maximum number of characters to be printed" No. One byte is for terminating null-character, so the maximum is 99 characters including the newline character if it exists. – MikeCAT Mar 24 '16 at 05:46
  • 1
    Also using magic number is not good and the line using `fgets()` should be `fgets(text,sizeof(text),fp);` Adding error check will make the code better. – MikeCAT Mar 24 '16 at 05:54
  • `sizeof(100)` -> `sizeof text` – M.M Mar 24 '16 at 06:14
0

Suppose the content of file input is:

Hello World

You can try the following code:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char ch;
    FILE *in;
    in = fopen("input","r");
    printf("The contents of the file are\n");
    while(fscanf(in, "%c", &ch) != EOF)
    {
        printf("%c",ch);
    }
    fclose(in);
    return 0;
}

Output:

The contents of the file are
Hello World
Ren
  • 2,852
  • 2
  • 23
  • 45
-1

You should use this:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char ch;
    FILE *in;

    /*Don't forget the extension (.txt)*/
    if(in = fopen("input.txt","r") == NULL);     
    {
        printf("File could not be opened\n");
    }
    else                                 
    {
       printf("The contents of the file are\n");
       /*I assume that you are reading char types*/
       fscanf(in,"%c",&ch);                   

       /*Check end-of-file indicator*/
       while(!feof(in))                      
       {
           printf("%c",ch);
           fscanf(in,"%c",&ch); 
       }
    }

    fclose(in);
    return 0;
}

You should bear in mind verify whether the file is open or not, it is always a good practice.

sonOFAthena
  • 108
  • 1
  • 6
  • 1
    It would be better to not test `feof`. [See here](http://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) for explanation. – M.M Mar 24 '16 at 06:13