0% found this document useful (0 votes)
15 views

Lecture 6

Uploaded by

10223025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Lecture 6

Uploaded by

10223025
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

Streams Formatted I/O

Working with Files

Nguyen Hai Van


Vietnamese-German University
[email protected]

Nguyen Hai Van Working with Files 1


Streams Formatted I/O

Introduction

Stream means any source of input or any destination for output.


Accessing a stream in a C program is done though a file pointer,
which has type FILE *(the FILE type is declared in <stdio.h>)
FILE *fp1, *fp2;
printf, scanf, putchar, getchar, puts, and gets- obtain input from stdin
and send output to stdout.

Nguyen Hai Van Working with Files 2


Streams Formatted I/O

Introduction

inputs can be obtained from a file instead of from the keyboard by


putting the name of the file on the command line, preceded by the <
character:
For example: demo <in.dat>
This technique, known as input redirection, essentially makes the
stdin stream represent a file (in.dat) instead of the keyboard.
Output redirection is similar.
demo < in.dat > out.dat
demo >out.dat <in.dat

Nguyen Hai Van Working with Files 3


Streams Formatted I/O

File operations-Opening a file

Syntax
FILE *fopen(const char * restrict filename, const char *restrict mode);

Explanation

First argument: a string containing the name of the file to be


opened. (A "file name" may include information about the file’s
location.
Second argument is a "mode string" that specifies what operations
we intend to perform on the file. The string "r", for instance, indicates
that data will be read from the file, but none will be written to it.

Nguyen Hai Van Working with Files 4


Streams Formatted I/O

File operations-Opening a file

Syntax
FILE *fopen(const char * restrict filename, const char *restrict mode);

Explanation

Example: fopen("c:\\ project\\test1.dat", "r")


fopen("c:/project/test1.dat", "r")
fopen return a file pointer that program can save in a variable and
use later whenever it needs to perform an operation on the file.
fp=fopen("in.dat", "r"); /* opens in.dat for reading*/

Nguyen Hai Van Working with Files 5


Streams Formatted I/O

modes for opening a file

String Meaning
r open a file in read mode
w opens or create a text file in write mode
a opens a file in append mode
w+ opens a file in both read and write mode, Create a file
a+ opens a file in both read and append mode
r+ opens a file in both read and write mode

Nguyen Hai Van Working with Files 6


Streams Formatted I/O

Closing a File

Syntax
int fclose(FILE *stream);

Nguyen Hai Van Working with Files 7


Streams Formatted I/O

Closing a File

It returns the error code EOF if the file was closed unsuccessfully,
otherwise it returns zero.

Nguyen Hai Van Working with Files 7


Streams Formatted I/O

Closing a File

Example
# include <stdio.h>
# include <stdlib.h>
# define FILE_ NAME "example.dat"
int main(void)
{
FILE *fp;
fp=fopen(FILE_ NAME, "r");
if (fp==NULL)
{
printf("Can’t open %s \n", FILE_NAME);
exit(EXIT_FAILURE);
}
fclose(fp);
return 0;
}

Nguyen Hai Van Working with Files 7


Streams Formatted I/O

Closing a File

Example
# include <stdio.h>
# include <stdlib.h>
# define FILE_ NAME "example.dat"
int main(void)
{
FILE *fp;
if (fopen(FILE_ NAME, "r")==NULL)
{
printf("Can’t open %s \n", FILE_NAME);
exit(EXIT_FAILURE);
}
fclose(fp);
return 0;
}

Nguyen Hai Van Working with Files 7


Streams Formatted I/O

Attaching a File to an Open Stream

Syntax
FILE *freopen(const char * restrict filename, const char * restricit mode,
FILE * restrict stream);

Instruction
freopen attaches a different file to a stream that’s already open. The most
common use of freopen is to associate a file with one of the standard
streams (stdin, stdout, or stderr).
freopen’s normal return value is its third argument (a file pointer), if it
can’t open the new file, freopen returns a null pointer

Nguyen Hai Van Working with Files 8


Streams Formatted I/O

Practice

Please write the program to check whether a file can be opened for
reading

Nguyen Hai Van Working with Files 9


Streams Formatted I/O

Solution

# include<stdio.h>
# include<stdlib.h>
int main()
{
FILE *fp;
if ((fp=fopen("filename", "r"))==NULL)
{ printf("% s can’t be opened \ n",filename);
exit(EXIT_FAILURE);
}
printf("% s can be opened \ n", filename);
fclose(fp);
return 0;
}

Nguyen Hai Van Working with Files 10


Streams Formatted I/O

Solution

int canCreateFile(char* path)


{
FILE *file = fopen(path, "w");
if(file)
{
fclose(file);
return 1;
}
return 0;
}

Nguyen Hai Van Working with Files 11


Streams Formatted I/O

Solution

# include<stdio.h>
# include<stdlib.h>
int main(int argc, char *argv[])
{
FILE *fp; if (argc !=2)
{
printf("usage: canopen filename \ n");
exit(EXIT_FAILURE);
}
if ((fp=fopen(argv[1], "r"))==NULL)
{ printf("% s can’t be opened \ n", argv[1]);
exit(EXIT_FAILURE);
}
printf("% s can be opened \ n", argv[1]);
fclose(fp);
return 0;
}

Nguyen Hai Van Working with Files 12


Streams Formatted I/O

The ... fprintf Function

Syntax
int fprintf (FILE * restrict stream,
const char * restrict format, ...);
int printf (const char * restrict format, ...);

Instruction
The fprintf and printf functions write a variable number of data items to an
output stream, using a format string to control the appearance of the
output.

Example
fprintf(fp, "total: % d\ n",total);

Nguyen Hai Van Working with Files 13


Streams Formatted I/O

The fscanf Function

Syntax
int fscanf (FILE * restrict stream,
const char * restrict format, ...);
int scanf (const char * restrict format, ...);

Instruction
The fscanf and scanf functions read data from an input string to indicate
the layout of the input. After the format string, any number of
pointers-each pointing to an object- follow as additional arguments.

Example
fscanf(fp, "%d",& total);

Nguyen Hai Van Working with Files 14


Streams Formatted I/O

Detechting End-of-File and Error Conditions

Syntax
void clearerr(FILE *stream);
int feof(FILE *stream);
int ferror(FILE *stream);

Nguyen Hai Van Working with Files 15


Streams Formatted I/O

Character I/O

Output Functions
int fputc(int c, FILE *stream);
int putc(int c, FILE *stream);
int putchar(int c);

Nguyen Hai Van Working with Files 16


Streams Formatted I/O

Input Functions

Input Functions
int fgetc(char *str, int n, FILE *stream);
int getc( FILE *stream);
int ungetc(int c, FILE *stream);

Nguyen Hai Van Working with Files 17


Streams Formatted I/O

Example

Discussion
The program opens a file named letters.txt and prints A through Z into
the file

Nguyen Hai Van Working with Files 18


Streams Formatted I/O

Example

Solution
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
int main()
{
char letter;
int i;
fptr = fopen("C:\\deanwork\\documents\\letters.txt", "w+");
if (fptr == 0)
{
printf("There was an error while opening the file.\n");
exit(1);
}
for (letter = ’A’; letter <= ’Z’; letter++)
{

Nguyen Hai Van Working with Files 19


Streams Formatted I/O

Example

Solution
fputc(letter, fptr);
}
puts("Just wrote the letters A through Z");
// Now read the file backwards
fseek(fptr, -1, SEEK_END); // Minus 1 byte from the end
printf("Here is the file backwards:\n");
for (i = 26; i > 0; i–)
{
letter = fgetc(fptr);
// Reads a letter, then backs up 2
fseek(fptr, -2, SEEK_CUR);
printf("The next letter is %c.\n", letter);
}
fclose(fptr); // Again, always close your files
return 0;
}

Nguyen Hai Van Working with Files 20


Streams Formatted I/O

Example

Example
Write a program that reads each line from the file and outputs it to the
screen.

Nguyen Hai Van Working with Files 21


Streams Formatted I/O

Example

Solution
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
int main()
{
char fileLine[100]; // Will hold each line of input
fptr = fopen("C:\\users\\DeanWork\\Documents\\BookInfo.txt","r");
if (fptr != 0)
{
while (!feof(fptr))
{
fgets(fileLine, 100, fptr);
if (!feof(fptr))
{
puts(fileLine);
}
}
}
Nguyen Hai Van Working with Files 22
Streams Formatted I/O

Example

fprintf()
The program opens the existing book info file from the first and adds a
line to the end.

Nguyen Hai Van Working with Files 23


Streams Formatted I/O

Example

fprintf()
#include <stdio.h>
#include <stdlib.h>
FILE * fptr;
int main()
{
fptr = fopen("C:\\users\\DeanWork\\Documents\\BookInfo.txt","a");
if (fptr == 0)
{
printf("Error opening the file! Sorry!\n");
exit (1);
}
// Adds the line at the end
fprintf(fptr, "\n More books to come!\n");
fclose(fptr); // Always close your files
return 0;
}

Nguyen Hai Van Working with Files 24


Streams Formatted I/O

Copying a file

Copying a file
fcopy f1.c f2.c

Nguyen Hai Van Working with Files 25


Streams Formatted I/O

File Positioning

File Positioning
int fgetpos(FILE *restrict stream,
fpos_ t *restrict pos);
int fseek(FILE *restrict stream,
long int offset, int whence);
int fsetpos(FILE *restrict stream, const fpos_ t *pos);

Instruction
every stream has an associated file position, a file is opened, the file
position is set at the beginning of the file. (If the file is opened in "append"
mode, however, the initial file position may be at the beginning or end of
the file, depending on the implementation.)
fseek function changes the file position associated with the first argument
(a file pointer). The third argument specifies whether the new position is to
be calculated with respect to the beginning of the file, the current position,
or the end of the file, <stdio.h> defines threee macros for this purpose:
SEEK_ SET Beginning of the file SEEK_ CUR Current file position SEEK_
END End of the file

Nguyen Hai Van Working with Files 26

You might also like