C Language Exercises:
1. Read 10 characters from the keyboard and display the 10 characters (need to use the read and write functions)
2. Write 5 characters into a text file
Question 1. C language once involved in the file operation problem, in fact, the biggest problem is the problem of pointers. Due to the fact that the pointer is still at the end of the file after writing, you need to manually return the pointer to the
#include <stdio.h> #include <unistd.h> #include <fcntl.h> #include <stdlib.h> #include < string.h> #include <time.h> #include <sys/types.h>int main () {int Fd,fd1,fd2,n,m,i,len;char C;char buff[ 10];char Buf[10];fd=open ("./test1.txt", o_rdwr| o_creat,755); Fd1=open ("./test2.txt", o_rdwr| o_trunc| o_creat,755); N=write (fd, "Hello", 5);p rintf ("Please input string:") scanf ("%s", buff); Len=strlen (buff); if (len>10 {perror ("The string is error restart");} M=write (Fd1,buff,len);p rintf ("%d\n", M), M=lseek (fd1,-m,seek_cur);p rintf ("%d\n", m); Read (fd1,buf,10);p rintf ("We Get output string:%s ", buf); close (FD); close (FD1); return 0;}
When manipulating files read and write, be sure to pay attention to where the pointer is pointing, otherwise you will not be able to read the data correctly
C language reading and writing exercises under Linux (read keyboard input)