C input & output

When we refer to input, this means filling the program with some data. Input can be in the form of a file or from the command line. The C language provides a series of built-in functions to read a given input and fill it into the program as needed.

When we refer to output, it means to display some data on the screen, on the printer, or in any file. C language provides a series of built-in functions to output data to the computer screen and save data to text files or binary files.

Standard Document

C language treats all devices as files. So devices (such as displays) are processed in the same way as files. The following three files will be automatically opened when the program is executed in order to access the keyboard and screen.

Standard Document File pointer equipment
Standard input stdin keyboard
Standard output stdout screen
Standard error stderr screen
#include <stdio.h>      // 执行 printf() 函数需要该库
int main()
{
    
    
    printf("f");  //显示引号中的内容
    return 0;
}
  • All C language programs need to include the main() function. The code starts execution from the main() function.
  • printf() is used to format the output to the screen. The printf() function is declared in the "stdio.h" header file.
  • stdio.h is a header file (standard input and output header file) and #include is a preprocessing command used to include header files. When the compiler encounters the printf() function, if it does not find the stdio.h header file, a compilation error will occur.
  • The return 0; statement is used to indicate exit from the program.

%d formatted output integer

#include <stdio.h>
int main()
{
    
    
    int testInteger = 5;
    printf("Number = %d", testInteger);
    return 0;
}
  • Use "%d" (integer) in the quotes of the printf() function to match the integer variable testInteger and output it to the screen.

%f formatted output floating point data

#include <stdio.h>
int main()
{
    
    
    float f;
    printf("Enter a number: ");
    // %f 匹配浮点型数据
    scanf("%f",&f);
    printf("Value = %f", f);
    return 0;
}

getchar() & putchar() functions

  • The int getchar(void) function reads the next available character from the screen and returns it as an integer. This function will only read a single character at the same time. You can use this method inside a loop to read multiple characters from the screen.

  • The int putchar(int c) function outputs characters to the screen and returns the same characters. This function will only output a single character at the same time. You can use this method in a loop to output multiple characters on the screen.

#include <stdio.h>
 
int main( )
{
    
    
   int c;
 
   printf( "Enter a value :");
   c = getchar( );
 
   printf( "\nYou entered: ");
   putchar( c );
   printf( "\n");
   return 0;
}

When the above code is compiled and executed, it will wait for you to enter some text. When you enter a text and press the Enter key, the program will continue and only read a single character, as shown below:

Enter a value :abc

You entered: a

scanf() and printf() functions

  • The int scanf(const char *format, …) function reads input from the standard input stream stdin and browses the input according to the provided format.

  • The int printf(const char *format, …) function writes the output to the standard output stream stdout and produces output according to the provided format.

format can be a simple constant string, but you can specify %s, %d, %c, %f, etc. to output or read strings, integers, characters, or floating-point numbers. There are many other format options available, which can be used as needed. For complete details, you can check the reference manuals of these functions.

#include <stdio.h>
int main( ) {
    
    
 
   char str[100];
   int i;
 
   printf( "Enter a value :");
   scanf("%s %d", str, &i);
 
   printf( "\nYou entered: %s %d ", str, i);
   printf("\n");
   return 0;
}

When the above code is compiled and executed, it will wait for you to enter some text. When you enter a text and press the Enter key, the program will continue and read the input, as shown below:

Enter a value :abc 123
You entered: abc 123 

Here, it should be noted that scanf() expects the input format to be the same as the %s and %d you gave, which means you must provide valid input, such as "string integer", if you provide "string string" or "integer integer", it will be considered as an incorrect input. In addition, when reading a string, scanf() will stop reading as long as it encounters a space, so "this is test" is three strings for scanf().

File read and write

A file, whether it is a text file or a binary file, represents a series of bytes. The C language not only provides access to the top-level functions, but also provides the bottom-level (OS) calls to process files on the storage device.

open a file

You can use the fopen() function to create a new file or open an existing file. This call will initialize an object of type FILE. The type FILE contains all the necessary information to control the flow. Here is the prototype of this function call:

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

Here, filename is a string used to name the file, and the value of the access mode mode can be one of the following values:

mode description
r Open an existing text file and allow the file to be read.
w Open a text file and allow writing to the file. If the file does not exist, a new file will be created. Here, your program will write content from the beginning of the file. If the file exists, it will be truncated to zero length and rewritten.
a Open a text file and write to the file in append mode. If the file does not exist, a new file will be created. Here, your program will append content to the existing file content.
r+ Open a text file, allowing read and write files.
w+ Open a text file, allowing reading and writing of the file. If the file already exists, the file will be truncated to zero length, if the file does not exist, a new file will be created.
a+ Open a text file, allowing read and write files. If the file does not exist, a new file will be created. Reading will start from the beginning of the file, and writing can only be in append mode.

If you are processing a binary file, you need to use the following access mode to replace the above access mode:
"rb", "wb", "ab", "rb+", "r+b", "wb+", "w+ b", "ab+", "a+b"

Close file

In order to close the file, use the fclose() function. The prototype of the function is as follows:

 int fclose( FILE *fp );

The function fputc() writes the character value of the parameter c into the output stream pointed to by fp. If the writing is successful, it will return the written character, if an error occurs, it will return EOF. You can use the following function to write a null-terminated string to the stream:

int fputs( const char *s, FILE *fp );

The function fputs() writes the string s into the output stream pointed to by fp. If the write is successful, it will return a non-negative value, if an error occurs, it will return EOF. You can also use the int fprintf(FILE *fp,const char *format, …) function to write a character string to a file. Try the following example:
Note: Please make sure you have a usable tmp directory. If the directory does not exist, you need to create it on your computer first.
/tmp is generally a temporary directory on a Linux system. If you are running on a Windows system, you need to modify it to an existing directory in the local environment, such as: C:\tmp, D:\tmp, etc.

#include <stdio.h>
 
int main()
{
    
    
   FILE *fp = NULL;
 
   fp = fopen("/tmp/test.txt", "w+");
   fprintf(fp, "This is testing for fprintf...\n");
   fputs("This is testing for fputs...\n", fp);
   fclose(fp);
}

When the above code is compiled and executed, it will create a new file test.txt in the /tmp directory and write two lines using two different functions.

Read file

Here is the simplest function to read a single character from a file:

int fgetc( FILE * fp );

The fgetc() function reads a character from the input file pointed to by fp. The return value is the character read, and EOF is returned if an error occurs. The following function allows you to read a string from the stream:

char *fgets( char *buf, int n, FILE *fp );

The function fgets() reads n-1 characters from the input stream pointed to by fp. It will copy the read string to the buffer buf, and append a null character at the end to terminate the string.

If this function encounters a newline character'\n' or EOF at the end of the file before reading the last character, it will only return the characters read, including the newline character. You can also use the int fscanf(FILE *fp, const char *format, …) function to read a string from a file, but it will stop reading when it encounters the first space and newline character.

#include <stdio.h>
 
int main()
{
    
    
   FILE *fp = NULL;
   char buff[255];
 
   fp = fopen("/tmp/test.txt", "r");
   fscanf(fp, "%s", buff);
   printf("1: %s\n", buff );
 
   fgets(buff, 255, (FILE*)fp);
   printf("2: %s\n", buff );
   
   fgets(buff, 255, (FILE*)fp);
   printf("3: %s\n", buff );
   fclose(fp);
 
}

When the above code is compiled and executed, it will read the file created in the previous part and produce the following results:

1: This
2: is testing for fprintf...

3: This is testing for fputs...

First, the fscanf() method only reads This, because it encountered a space after it. Second, call fgets() to read the remaining part until the end of the line. Finally, call fgets() to read the second line completely.

Binary I/O function

The following two functions are used for binary input and output:

size_t fread(void *ptr, size_t size_of_elements, 
             size_t number_of_elements, FILE *a_file);
              
size_t fwrite(const void *ptr, size_t size_of_elements, 
             size_t number_of_elements, FILE *a_file);

Both functions are used to read and write storage blocks-usually arrays or structures.

Guess you like

Origin blog.csdn.net/yasuofenglei/article/details/107813583