Files


Standard library functions:

  1.    File access

function to open a file  à  fopen()
function to close a file  à  fclose()

e.g
fptr = fopen(“ <filename>”, “mode”);
a filename can be à abc.txt
mode à r (read)  or  w (write)
   
2. Operations on a file

function to remove (remove) and rename (rename) a file
 
         3. Formatted I/O

           fscanf, scanf, sscanf
           fprintf, printf,sprintf

          4.  character I/O

          functions for reading strings à fgets(), gets()
          functions for writing strings à fputc(), putc(), puts()

 5.    Direct I/O
functions  to read (fread) and write (fwrite)

6.    Error handling
Functions to test whether EOF returned by a function indicates an end end of file or error                         (feof and ferror )
feof() à returns a zero if end of file is not reached.

7.    File positioning
fseek() à To set the file position to a specified portion of the file
ftell() à to interrogate the current file position
rewind() à To reset the file position to the beginning of the file

file access?

FILE *fptr;
fptr = fopen(“pgm.c”, “w”);

Reading from a file:
fgetc()  à reads first character from the current pointer and advances the pointer to the next character

Q1?
Program to read a file and count the characters?

main()
{
FILE *fptr;
char ch;
int noc =0;
fptr = fopen(“pgm.c”, “r”);
while(1)
{
ch = fgetc(fptr);
if (ch ==EOF)
break;
noc++;
}
fclose(fptr);
printf(“\n Number of characters= %d”, noc);
}

Writing to a file:

          fputc(ch,fptr)

main()
{
FILE *fs,*ft;
char ch;
fs = fopen(“pgm1.c”, “r”);
if(fs==NULL)
{
puts(“cannot open the file”);
exit(1);
}

ft = fopen(“pgm2.c”, “r”);
if (ft == NULL)
{
puts(“cannot open the file”);
fclose(fs);
exit(1);
}

while(1)
{
ch = fgetc(fs);
if (ch ==EOF)
break;
else
fputc(ch,ft);
}
fclose(fs);
fclose(ft);
}

Q3. Count number of chars, spaces or blanks and newlines in a file?

main()
{
FILE *fptr;
char ch;
int noc =0,nob=0,nol=0;

fptr = fopen(“pgm.c”, “r”);

while(1)
{
ch = fgetc(fptr);
if (ch ==EOF)
break;
noc++;
if (ch == ‘  ’) nob++;
if (ch == ‘\n ’) nol++;

}
fclose(fptr);
printf(“\n Number of characters= %d”, noc);
printf(“\n Number of spaces = %d”, nob);
printf(“\n Number of lines = %d”, nol);
}

Q4. Receive a string from keyboard and write to a file?

main()
{
FILE *fptr;
char s[25];
fptr = fopen(“abc.txt”, “w”);
if(fptr == NULL)
{
puts(“cannot open the file”);
exit(1);
}
printf(“enter few lines of text”);
printf(“To stop this program – press Enetr”);
while(strlen(gets(s))>0)
{
fputs(s,fptr);
fputs(“\n”);
}
fclose(fptr);
}


No comments:

Post a Comment