• C

Using fopen...

I need you to tell me how can I open an existing txt file using fopen.
I have my txt file in a: called hello.txt and need it to be displayed in my C program.
Please could you explain me deeply the use of fopen and if it can be use to open any kind of files?.

Thanks.
gothic130Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
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.

Gratch06Commented:
Here's some simple code to do what you want.

#include <stdio.h>

int main ()
{
  FILE * myFile;
  myFile = fopen ("A:\\hello.txt","rt"); //rt = read only, text mode.
  if (myFile!=NULL) //Check if we actually DO have a file.
  {
    //Do your processing of the file here.
    fclose (myFile); //close the file
  }
  return 0;
}
0
gothic130Author Commented:
>>//Do your processing of the file here.

You mean that this is where I should put printf?
0
sunnycoderCommented:
     FILE *fopen (const char *path, const char *mode);

DESCRIPTION
       The fopen function opens the file whose name is the string pointed to by path and associates a stream with it.

       The argument mode points to a string beginning with one of the following sequences (Additional characters may follow these sequences.):

       r      Open text file for reading.  The stream is positioned at the beginning of the file.

       r+     Open for reading and writing.  The stream is positioned at the beginning of the file.

       w      Truncate file to zero length or create text file for writing.  The stream is positioned at the beginning of the file.

       w+     Open  for  reading  and  writing.   The file is created if it does not exist, otherwise it is truncated.  The stream is positioned at the beginning of the file.

       a      Open for writing.  The file is created if it does not exist.  The stream is positioned at the end of the file.

       a+     Open for reading and writing.  The file is created if it does not exist.  The stream is positioned at the end of the file.

       The mode string can also include the letter ``b'' either as a last character or as a character between the characters in any of the  two-charac­ter  strings  described above.  This is strictly for compatibility with ANSI X3.159-1989 (``ANSI C'') and has no effect; the ``b'' is ignored on all POSIX conforming systems, including Linux.  (Other systems may treat text files and binary files differently, and adding the ``b'' may be  a  good idea if you do I/O to a binary file and expect that your program may be ported to non-Unix environments.)

       Any  created files will have mode S_IRUSR|S_IWUSR|S_IRGRP|S_IWGRP|S_IROTH|S_IWOTH (0666), as modified by the process' umask value (see umask(2).

       Reads and writes may be intermixed on read/write streams in any order.  Note that ANSI C requires that a  file  positioning  function  intervene between output and input, unless an input operation encounters end-of-file.  (If this condition is not met, then a read is allowed to return the     result of writes other than the most recent.)  Therefore it is good practice (and indeed sometimes necessary under Linux) to  put  an  fseek  or  fgetpos  operation  between write and read operations on such a stream.  This operation may be an apparent no-op (as in fseek(..., 0L, SEEK_CUR) called for its synchronizing side effect.

RETURN VALUE
       Upon successful completion fopen, fdopen and freopen return a FILE pointer.  Otherwise, NULL is returned and the global variable errno is set to indicate the error.


#include <stdio.h>

int main ()
{
        FILE * myFile;
         char buffer[256];
         myFile = fopen ("A:\\hello.txt","rt"); //rt = read only, text mode.
        if (myFile!=NULL) //Check if we actually DO have a file.
        {
                 while ( fgets ( buffer, 256, myfile ) != NULL ) //read in line by line
                              printf ( " %s ", buffer );    //print the line read
                 fclose (myFile); //close the file
        }
        return 0;
}
0

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
IT Pros Agree: AI and Machine Learning Key

We’d all like to think our company’s data is well protected, but when you ask IT professionals they admit the data probably is not as safe as it could be.

Gratch06Commented:
>>You mean that this is where I should put printf?
Ya...sunnycoder's answer is a bit more complete, adding in the input from file and print functionality to the code.  I figured by the tenor of your initial question that you knew the correct operations once the file was open, just not how to properly open it.  Also, you can do a lot more with a file than simply print its contents, and I didn't want to just provide the one basic case, but rather left it a bit more open ended, though reading over your question again, it is clear that you wanted to print its contents (why it wasn't initially, that I do not know :)
0
ssnkumarCommented:
>>//Do your processing of the file here.

>You mean that this is where I should put printf?

Yes, you can do printf at that point......bUt, before that you need to read the contents of the file. Use fgets() or fread() for this.
0
jinumjoyCommented:
dont you have access to a Linux box?

use

#man fopen    /* to get manual on fopen() */
#man fget()    /* to get manual on fget() */
#man fread()  /* to get manual on fread() */
.
.
.

this is the best way to know about a standard library function.

sunnycoder your explanation of fopen() was real good... ;)

-Jinu
0
gothic130Author Commented:
Thank you very much to all. I was very helpful for the last part of my C course in my school.
0
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
C

From novice to tech pro — start learning today.