• C


Hello, I'm learning how to use files in C language ,
and there's something I don't understand
- In my file :

- In my pgm :
printf("%d\n", ftell(filein));   // 0
printf("%c\n", fgetc(filein)); // H
printf("%d\n", ftell(filein));   // 1

then with a fseek i go at 5th position, just before the \n\r

printf("%d\n", ftell(filein));   // 5
printf("%c\n", fgetc(filein)); // <new line>
printf("%d\n", ftell(filein));   // 7

But I tought fgetc would only take the '\n' cause fgetc takes one char ...
Why it takes both in one time ?

Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Jaime OlivaresSoftware ArchitectCommented:
I guess it is due you have opened your file as 'text', something like:

filein = fopen("yourfile.txt", "rt");

Try to open your file as binary:

filein = fopen("yourfile.txt", "rb");
Different platforms use different characters for ending lines of text, which can be a problem for writing portable software.  The C library's solution is to abstract the format, so that from a C program's point of view, all text files have lines terminated with '\n'.  The library takes care of translating between a newline character in its application programming interface and whatever the target platform actually uses, so one can write portable text-processing programs.  This translation is probably what happened in your case.

Opening a file in text mode turns this abstraction on, and opening a file in binary mode turns it off.  That's why jaime_olivares suggested opening it in binary mode, assuming your goal is to be able to read the characters that are actually in the file.


Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
matthew016Author Commented:
Thanks, very good
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.