amulous
amulous

Reputation: 732

How to print the first character in a file using the members of the FILE structure?

#include<stdio.h>
int main()
{
FILE  *fp;
fp = fopen("test22.txt","r");
while(fgetc(fp)!=EOF)
printf("%c",*(fp->_ptr));
return 0;
}

I am using Code::Blocks. I know that the '_ptr' member points to the next character in the buffer. The file's contains the text 'Hello World!'. How do I modify my program to print the first character too, using just the members of FILE structure?

Upvotes: 0

Views: 1028

Answers (4)

bptfreitas
bptfreitas

Reputation: 16

One possible solution is to take advantage of the "return reference on assignment", which means that, after such operation, it is returned a reference to its result, which can be then used, for example, to compare to the EOF.

Using your code:

#include<stdio.h>
int main()
{
    FILE  *fp;
    fp = fopen("text22.txt","r");
    char buffer;
    while((buffer=fgetc(fp))!=EOF)
        printf("%c",buf);
    return 0;
}

Upvotes: 0

levengli
levengli

Reputation: 1121

Using the members of the FILE type is extremely risky and non-portable. While _ptr may point to the currently cached portion of the stream, there is absolutely no guarantee that _ptr[0] will always point at the first character in the file. See here where it states:

The content of a FILE object is not meant to be accessed from outside the functions of the and headers; In fact, portable programs shall only use them in the form of pointers to identify streams, since for some implementations, even the value of the pointer itself could be significant to identify the stream (i.e., the pointer to a copy of a FILE object could be interpreted differently than a pointer to the original).

Upvotes: 1

Varvarigos Emmanouil
Varvarigos Emmanouil

Reputation: 757

#include<stdio.h>
int main()
{
    FILE  *fp;
    fp = fopen("test22.txt","r");
    if(fp == NULL){
        printf("File did not opened.\n");
        return -1;
    do{
        printf("%c",*(fp->_ptr));
    } while(fgetc(fp)!=EOF);
    fclose(fp);
    return 0;
}

Upvotes: 1

vroomfondel
vroomfondel

Reputation: 3106

fgetc advances the buffer to the next character. You can save/print the first letter before the fgetc call, use a do-while, call rewind, etc.

Upvotes: 0

Related Questions