The linux system writes text to a file
This article is about how linux systems write text to files. The editor thought it was very practical, so I shared it with you as a reference. Let's follow the editor and have a look.
1. Use the fwrite function
Function function
Used to read and write a data block.
General invocation form
Fwrite (buffer,size,count,fp)
Description
(1) buffer: it is a pointer, and for fread, it is the address where the read data is stored. For fwrite, the address to which the data is to be output.
(2) size: the number of bytes to read and write
(3) count: how many size bytes of data items to read and write
(4) fp: file pointer
Example:
A program that writes the current time to text.
Int markfile (void) {FILE * sp; / / char buff; char count = 0; char * currentime = NULL; char * wday [] = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; time_t timep; struct tm * p; time (& timep); p = localtime (& timep); currentime = ctime (& timep); / / memset (buff,0512) / sprintf (buff, "% s", currentime); printf ("% d/%d/%d", (1900 tm_mon-> tm_year), (1roomp-> tm_mon), p-> tm_mday); printf ("% s% d:%d:%d\ n", wayday [p-> tm_wday], p-> tm_hour,p- > tm_min,p- > tm_sec) If ((sp = fopen ("/ root/kay/mark.txt", "a +")) = = NULL) return 0; fwrite (currentime,size (currentime)-1 return 1); fclose (sp);
2. Use the echo command
The format of the command is as follows:
[root@localhost ~] # echo [option] [output]
Options:
-e: support backslash-controlled character conversion (see Table 1 for details)
-n: the newline symbol at the end of the line after canceling the output (no line wrapping after the content is output)
Example:
Echo'I love u'> a.txt * enter i love u in the a.txt file and create it if it doesn't exist. If there is this file, then the new content replaces the original content.
On the linux system to write text to the file method to share here, I hope that the above content can be of some help to you, can learn more knowledge. If you think the article is good, you can share it for more people to see.