简体   繁体   中英

Why doesnt my C program work? reading from a file

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;
}

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" ?

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);

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM