Reading a file one char at a time

混江龙づ霸主 提交于 2019-12-07 22:53:48

问题


I have two .c files: one contains the main and the other contains all of my functions.

In my main I have a part where I want to read a char at a time the loop looks like this:

while(ch = ReadFile(fp)) != EOF)
{
    // Code
}

where ch is an integer (int ch;) and fp is a file pointer (FILE* fp;).

And (different .c file ---):

int ReadFile(FILE* fp)
{
    // Some code
    return n; // The next char
}

Does anyone know how I can read one char at a time from the main this way, using this method?


回答1:


Update:-

The famous getc from <stdio.h> is a solution:-

while((ch = getc(fp)) != EOF)
    {
      //...
    } 
...
int ReadFile(FILE* fp)
{
   //Do what you wish... :)
  return getc(fp); 
}

Declared as int getc( FILE * _File);




回答2:


try this:

int ReadFile(FILE* fp, int *buffer)
{
    if(fp != NULL)
    {
        *buffer = fgetc(fp);
        return *buffer;
    }
    else return NULL;
}



回答3:


Simply:

while(ch != EOF)
{ 
    ch = fgetc(fp);
    //process ch
}

Keep in mind that fgetc is declared as an int.

Or if you wanted to build a string char by char you could read the file char by char to dynamically allocated memory like so (assuming fp is open for reading):

char *data = NULL, *tmp;
int ch, bff = 0;

while(ch != EOF)
{
    if(!(tmp = realloc(data, bff + 2)))
    {
        free(data);
        return 1;
    }
    data = tmp;
    ch = fgetc(fp);   //or your readfile function assuming it works the same as fgetc
    data[bff++] = ch;
}
data[bff] = '\0';

just free(data) when you are done with it



来源:https://stackoverflow.com/questions/12269125/reading-a-file-one-char-at-a-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!