简体   繁体   中英

Reading input file in C

I need to read from an input file by using C programming language to do one of my assignments.

Here's my code:

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

int main(int argc, char *argv[])
{
    char *input = readFromFile(argv);
    return 0;
}

char *readFromFile(char *argv[])
{
    FILE *fp;
    fp = fopen(argv[1],"r");
    char *input, c;
    int i = 0;

    while(!feof(fp))
    {
        c = fgetc(fp);
        input[i++] = c;
    }
    fclose(fp);
    return input;
}

I want to do this reading operation in another function, not in function main() . I tried, but couldn't do it.

When I try to do it with the code above, I get an error message that says:

conflicting types for readFromFile()

How can I fix this error and do what I want?

You have to declare readFromFile before using it. The best way to do this is to add a prototype:

char *readFromFile(char *argv[]); /* note that the identifier is useless here */

NB : By the way, there is a lot of other errors in your source code. The main one is that you don't allocate memory for input . Therefore, you will try to dereference an unitialized pointer: this leads to an undefined behavior. Since you are returning your pointer, you need to use dynamic allocation.

#include <stdlib.h>
char *input = malloc(SIZE);

Moreover, your utilisation of feof is wrong.

First of all you can choose between these:

1. Declare the function prototype;
2. Declare the function before the main.

This way the function is recognized in main.To be fast I always declare function before the main.In readFromFile you aren't allocating the memory that you need, fixed it for you:

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

char *readFromFile(char *argv[])
{
    FILE *fp;
    fp = fopen(argv[1],"r");
    char *input, c;
    int i = 0;
    size_t size=100*sizeof(char);
    input=(char*)malloc(size);

    while( (c = fgetc(fp)) != EOF )
    {
        if(++i == size)
        {
            size+= 100*sizeof(char);
            input=(char*)realloc(input,size);
        }
        input[i-1] = c;
    }
    fclose(fp);
    return input;
}

int main(int argc, char *argv[])
{
    char *input = readFromFile(argv);
    return 0;
}

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