You are here:

C/Text Files

Advertisement


Question
How do you open an existing text file in a read only mode?

Answer
Dear Tumelo Quest

First, I'd like to apologise for the delay in replying. About your question about opening an existing text file in read only mode, here is the answer:

First make sure your file is created and the last character in it is the 'Enter' key. Now let's assume the name of the file is abc.txt. Here is the code for you:

#include<stdio.h>
#define NULL 0
void main(){
FILE *fp;
char c;
if((fp=fopen("abc.txt","r"))==NULL){         //this is the function (fopen())that'll open an
                                            //existing txt file in the read only mode - "r"
  printf("Cannot open the file");}
else
  do
     putchar(c=getc(fp));
  while(c!='\n');
fclose(fp);
getch();
}

The fopen function takes 2 arguments. The first one is the name of the file to be opened, the second is the mode in which it sould be opened. "r" - denotes opening the file in read only mode.

Regards
Smitha Renny

C

All Answers


Answers by Expert:


Ask Experts

Volunteer


Smitha Renny

Expertise

I can answer questions related to basic understanding of C concepts, arrays, pointers and their handling well.

Experience

I've been programming in BASIC since 1987. Later moved onto Pascal for a short period and then hooked onto C since 1997.

Education/Credentials
I have completed a Post-Graduate diploma in Computer Applications. Currently doing MCA

©2012 About.com, a part of The New York Times Company. All rights reserved.