הנושא: קלט/פלט וקבצים הקורס: תכנות 1 סמסטר א' 2002/2001
INPUT/OUTPUT FUNCTIONS
1)Get a character
int fgetc( FILE *stream );
The fgetc function reads a single character from the current position of a file.
Return the character read as an int or return EOF to indicate an error or end of file.
int getchar( void );
Each of these routines reads a single character from a file or get a character from stdin (getchar) the current position and increments the associated file pointer (if defined) to point to the next character.
Each of these functions returns the character read. To indicate a read error or end-of-file condition, fgetc and getchar return EOF.
2) Put a character
int fputc( int c, FILE *stream );
int putchar( int c );
Each of these routines writes the single character c to the output stream at the current position. Any integer can be passed to fputc, but only the lower 8 bits are written. The putchar routine is identical to fputc( c, stdout ).
Each of these functions returns the character written. To indicate an error or end-of-file condition, the functions return EOF.
Example
/* This program uses fgetc and fputc to read words from the input file and place them into the output file with one space a separator. The maximal word size is 80 characters.
*/
#include <stdio.h>
#include <string.h
#include <stdlib.h
#define MAX 80
void main (){
FILE *source,*result;
char string [MAX+1];
char *save;
int ch, i=0, mode;
int length,start;
if((source=fopen("source.txt","r"))==NULL) {
printf("Can't open the file\n");
return;
}
if((result=fopen("result.txt","w"))==NULL) {
printf("Can't open the file\n");
return;
}
while((ch=fgetc(source))!=EOF)
if( ch!=' ')
string[i++]=ch;
else
if(i( {
string[i]='\0';
for(i=0; string[i]; i++)
fputc(string[i],result);
fputc(' ',result);
i=0;
}
if(i) {
string[i]='\0';
for(i=0; string[i]; i++)
fputc(string[i],result);
}
3) Get a string
char *fgets( char *string, int n, FILE *stream );
char *gets( char *buffer );
The fgets function reads characters from the current stream position to and including the first newline character, to the end of stream, or until the number of characters read is equal to n-1 , whichever comes first. The result stored in string is appended with a NULL character. The newline character, if read, is included in the string.
The gets function reads a line from the standard input stream stdin and stores it in buffer. The line consists of all characters up to and including the first newline character ('\n'). gets then replaces the newline character with a null character ('\0') before returning the line. In contrast, the fgets function retains the newline character.
The function returns its argument if successful. A NULL pointer indicates an error or end-of-file condition.
4)Put a string
int fputs( const char *string, FILE *stream );
int puts( const char *string );
The fputs function copies string to the output stream at the current position, returns a nonnegative value if it is successful. On an error, fputs returns EOF.
The puts function writes string to the standard output stream stdout, replacing the string's terminating null character ('\0') with a newline character ('\n') in the output stream.
Example
/* This program uses fgets to read lines from the input file. Than the program uses fputs to put words into the output file retaining one space between the words. The maximal line size is 80 characters.
*/
mode=1;
while(fgets(string,MAX+1,source)) {
save=string;
while(*(save((
if(mode) {
if((*(save)==' ')
mode=0;
save++;
{
else
if(*(save)!=' ') {
mode=1;
save++;
}
else
strcpy(save,save+1);
fputs(string,result);
{
5) Formatted Input/Output
int fscanf( FILE *stream, const char *format [, argument ]... );
int scanf( const char *format [,argument]... );
The fscanf function reads data from the current position of stream into the locations given by argument (if any). Each argument must be a pointer to a variable of a type that corresponds to a type specified in format (format Specification Fields see page 6). Format controls the interpretation of the input fields and has the same form and function as the format argument for scanf.
The function returns the number of fields successfully converted and assigned; the return value does not include fields that were read but not assigned. A return value of 0 indicates that no fields were assigned. If an error occurs, or if the end of the file stream is reached before the first conversion, the return value is EOF .
The scanf function reads data from the standard input stream stdin and writes the data into the location given by argument. Each argument must be a pointer to a variable of a type that corresponds to a type specified in format. If copying takes place between strings that overlap, the behavior is undefined.
int fprintf( FILE *stream, const char *format [, argument ]...);
int printf( const char *format [, argument]... );
The printf function formats and prints a series of characters and values to the standard output stream, stdout. If arguments follow the format string, the format string must contain specifications that determine the output format for the arguments. printf and fprintf behave identically except that printf writes output to stdout rather than to a destination of type FILE.
Each of these functions returns the number of characters printed, or a negative value if an error occurs.
Example
/* This program uses fscanf and fprintf to read words from the input file and place them into the output file with one space a separator. The maximal word size is 80 characters.
*/
while((fscanf(source,"%s",string))!=EOF)
fprintf(result,"%s ",string);
4)Unformatted Input / Output
size_t fread( void *buffer, size_t size, size_t count, FILE *stream );
The fread function reads up to count items of size bytes from the input stream and stores them in buffer. The file pointer associated with stream (if there is one) is increased by the number of bytes actually read. If the given stream is opened in text mode, carriage return–linefeed pairs are replaced with single linefeed characters. The replacement has no effect on the file pointer or the return value. The file-pointer position is indeterminate if an error occurs. The value of a partially read item cannot be determined.
The function returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count.
size_t fwrite( const void *buffer, size_t size, size_t count, FILE *stream );
The fwrite function writes up to count items, of size length each, from buffer to the output stream. The file pointer associated with stream (if there is one) is incremented by the number of bytes actually written. If stream is opened in text mode, each carriage return is replaced with a carriage-return – linefeed pair. The replacement has no effect on the return value.
The function returns the number of full items actually written, which may be less than count if an error occurs. Also, if an error occurs, the file-position indicator cannot be determined.
Example
/* This program uses fread to read data block from the input file. The program forms the lines do not exceed 80 characters and containing whole words. The program uses fwrite to write the formed lines into the output file.
*/
length=MAX;
start=0;
for(i=0;i<MAX;i++)
string[i]=' ';
while(fread(string+start,sizeof(char),length,source)) {
string[MAX]='\0';
for(i=MAX-1;i>=0;i--) {
if(string[i] ==' ')
break;
}
if(i<=0){
puts("Error");
return;
}
fwrite(string,sizeof(char),i,result);
fprintf(result,"\n");
strcpy(string,string+i+1);
length=i+1;
start=MAX -length;
for(i=start;i<MAX;i++)
string[i]=' ';
}
fscanf:
format Specification Fields:
A format specification has the following form:
%[*] [width] type
The type character, which appears after the last optional format field, determines whether the input field is interpreted as a character, a string, or a number
(%d -int, %f - float, %lf - double, %c - character, %s - string).
The simplest format specification contains only the percent sign and a type character (for example, %s).
An asterisk (*) following the percent sign suppresses assignment of the next input field, which is interpreted as a field of the specified type. The field is scanned but not stored.
Width Specification
width is a positive decimal integer controlling the maximum number of characters to be read from stdin. No more than width characters are converted and stored at the corresponding argument. Fewer than width characters may be read if a white-space character (space, tab, or newline) or a character that cannot be converted according to the given format occurs before width is reached.
To read strings not delimited by space characters, a set of characters in brackets ([ ]) can be substituted for the s (string) type character. The corresponding input field is read up to the first character that does not appear in the bracketed character set. If the first character in the set is a caret (^), the effect is reversed: The input field is read up to the first character that does appear in the rest of the character set.
Note that %[a-z] and %[z-a] are interpreted as equivalent to %[abcde...z].
To store a string without storing a terminating null character ('\0'), use the specification %nc where n is a decimal integer. In this case, the c type character indicates that the argument is a pointer to a character array. The next n characters are read from the input stream into the specified location, and no null character ('\0') is appended. If n is not specified, its default value is 1.
For example:
fscanf( ptr, "%20[^\n]%9d%*c", name, &id);
the function fscanf reads 20 characters or till newline ('\n') from the input stream and stores them in field name, then it reads the next 9 characters and converts them into integer id, then it reads one symbol which is not stored.
1