I/O in C Flashcards
What are the “standard” streams?
- stdin - standard input
- usually from input but can also be used when piping in unix
- stdout - standard output
- usually to screen but can also be used when piping in unix
- stderr - standard error
- usually to screen
note: #include <stdio.h> is required</stdio.h>
What using scanf, what operater is needed?
& is needed for int, floar or char but not needed with strings
How would you introduce error checking with scanf?
while(scanf(“%d”, &1) == 1){
//will loop while we have appropriate input
}
How would you skip blank spaces or dashes in the input stream?
scanf(“%d %d %d”, &day, &month, &year);
scanf(“%d-%d-%d”, &day,&month,&year);
How do you use fgets( ) and how do you specifify a maximum number of characters? How does this differ from fscanf( )? What does fscanf( ) return?
define MAX 81
char buffer[MAX];
fgets(buffer, MAX, stdin);
- reads from stdin, stores info in buffer up to the MAX-1 (it allows for the addition of the null terminating character)
fscanf( ) reads the whole line un buffered
- it returns the number of input items converted and assigned successfully
How do you open a file in C?
List the read modes.
FILE * inputfile = NULL;
inputfile = fopen(“names.txt”, “r”);
Read Modes:
- r - read only
- w - write to (overwriting current file if there is one)
- a - appends to the file
What are the basic file handling functions:
- fopen()
- fclose()
- fscanf()
- fprintf()
How do you error check the opening of a file?
File handler becomes NULL when an fopen() occurs
if(inputfile == NULL)
{
printf(“Unable to open input file.\n”);
return 1;//ends program if inside main function
}
How would you read a list of name from inputfile?
while(fscanf(inputfile, “%s”, name) == 1)
{
}
How would you open a file to write to, and then write to it?
FILE *outfile = null;
outfile = fopen(“name.txt”, “w”);
if (fprintf(“%s\n”, name) <= 0){printf(“error writing to file”); return 1;}
fputs(char * s, * filehandler);
This will not only write to the file but error check it at the same time.
How do you use:
- fgets()
- fputs()
- char *fgets(char *s, int n, FILE * fp)
- reads an entire line into s, up to n-1 characters in length
- returns the point s on success or NULL if error or EOF is reached
- (‘\n’) stops reading but is included in the string
- int fputs(char *s, FILE *fp);
- returns the number of characters written if successful, otherwise, return EOF