Writing and reading txt file
#include<stdio.h> #include<string.h> int main( int argc, char *argv[] ) { int rc=0; FILE *fp; char c[] = "<html> \r\n \ <head> \r\n \ <title>WEB RESTRICTION</title> \r\n \ </head> \r\n \ <body> \r\n \ <h1>WARRNING</h1> \r\n \ <p>YOU ARE NOT ALLOWED TO ACCESS THIS PAGE !!!</p> \r\n\ </ body> \ R & lt \ n-\ </ HTML> \ R & lt \ n- " ; char Buffer [ 20 is ]; / * Open file for reading and writing * / FP = the fopen ( " file.txt " , " W + " ); / * write data to a file * / fwrite (C, strlen (C) + . 1 , . 1 , FP); / * beginning of the lookup file * / fseek (FP, 0 , SEEK_SET); / * read and display the data * / fread (Buffer, strlen (C) + . 1 , . 1 , FP); the printf ("%s\n", buffer); fclose(fp); return rc; }
Reads the specified file txt
#include <stdio.h> #include < String .h> int main ( int argc, char * the argv []) { int RC = 0 ; the FILE * FP; char Buffer [ 256 ] = { 0 }; / * open file for reading and writing * / FP = the fopen ( " file.txt " , " R & lt " ); / * read and display the data * / fread (Buffer, the sizeof (Buffer), . 1 , FP); the printf ( "%s\n", buffer); fclose(fp); return rc; }
Reads one line
#include<stdio.h> #include<string.h> int main( int argc, char *argv[] ) { int rc=0; FILE *fp; char buffer[256]={0}; /* 打开文件用于读写 */ fp = fopen("file.txt", "r"); int len; if(fp != NULL){ while(fgets(buffer,256,fp) != NULL) { len = strlen(buffer); buffer[len-1] = '\0'; printf("0 %s\n", buffer); } fclose(fp); } printf("1 %s\n", buffer); return rc; } # gcc -o str.o str.c # ./str.o 0 dddddddddddddddd 0 ddddddddd 0 eeeeeeeeeeee 1 eeeeeeeeeeee