Solved

Using fopen...

Posted on 2003-11-16
7
874 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
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
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Preface I don't like visual development tools that are supposed to write a program for me. Even if it is Xcode and I can use Interface Builder. Yes, it is a perfect tool and has helped me a lot, mainly, in the beginning, when my programs were small…
This tutorial is posted by Aaron Wojnowski, administrator at SDKExpert.net.  To view more iPhone tutorials, visit www.sdkexpert.net. This is a very simple tutorial on finding the user's current location easily. In this tutorial, you will learn ho…
The goal of this video is to provide viewers with basic examples to understand opening and writing to files in the C programming language.
The goal of this video is to provide viewers with basic examples to understand opening and reading files in the C programming language.

705 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now