Solved

Using fopen...

Posted on 2003-11-16
7
879 Views
Last Modified: 2010-04-15
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.
0
Comment
Question by:gothic130
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 1

Assisted Solution

by:Gratch06
Gratch06 earned 200 total points
ID: 9760409
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
 

Author Comment

by:gothic130
ID: 9761124
>>//Do your processing of the file here.

You mean that this is where I should put printf?
0
 
LVL 45

Accepted Solution

by:
sunnycoder earned 300 total points
ID: 9761455
     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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Expert Comment

by:Gratch06
ID: 9761694
>>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
 
LVL 8

Expert Comment

by:ssnkumar
ID: 9761706
>>//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
 

Expert Comment

by:jinumjoy
ID: 9761784
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
 

Author Comment

by:gothic130
ID: 9774064
Thank you very much to all. I was very helpful for the last part of my C course in my school.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
valid enum? 6 75
Arduino EDI - Programming language 3 115
Unable to start eclipse ? 17 163
nested if statement in excel help 4 40
Windows programmers of the C/C++ variety, how many of you realise that since Window 9x Microsoft has been lying to you about what constitutes Unicode (http://en.wikipedia.org/wiki/Unicode)? They will have you believe that Unicode requires you to use…
This is a short and sweet, but (hopefully) to the point article. There seems to be some fundamental misunderstanding about the function prototype for the "main" function in C and C++, more specifically what type this function should return. I see so…
The goal of this video is to provide viewers with basic examples to understand how to use strings and some functions related to them in the C programming language.
Video by: Grant
The goal of this video is to provide viewers with basic examples to understand and use for-loops in the C programming language.

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question