|
发表于 2013-5-15 22:59:19
|
显示全部楼层
- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #define MAX_LEN 400
- struct Line {
- char content[MAX_LEN];
- struct Line* next;
- };
- struct MyFile {
- struct Line* pHead;
- struct Line* pTail;
- };
- void init( struct MyFile* pfile, const char* file_name );
- void write( struct MyFile* pfile, const char* file_name );
- void delete_line( struct MyFile* pfile, const char* line_content );
- void destroy( struct MyFile* pfile );
- int main (void) {
- struct MyFile file;
- init( &file, "C:\\data.txt" );
- delete_line( &file, "cccc" );
- write( &file, "C:\\data.txt" );
- destroy( &file );
- }
- struct Line* getLine( FILE * pf ) {
- struct Line* pLine = (struct Line*)malloc(sizeof(struct Line));
- pLine->next = 0;
- if( fgets( pLine->content, MAX_LEN ,pf ) ) {
- pLine->content[ strlen(pLine->content)-1 ]=0;//eat '\n'
- return pLine;
- }else {
- free(pLine);
- return 0;
- }
- }
- void init( struct MyFile* pfile, const char* file_name ) {
- FILE * pf = fopen( file_name, "r" );
- struct Line* pline;
- pfile->pHead = (struct Line*)malloc(sizeof(struct Line));//no use head
- pfile->pTail = 0;
- while( pline = getLine(pf) ) {
- if( pfile->pTail == 0 ) {
- pfile->pHead->next = pfile->pTail = pline;
- }else {
- pfile->pTail->next = pline;
- pfile->pTail = pline;
- }
- }
- fclose( pf );
- }
- void destroy( struct MyFile* pfile ) {
- while( pfile->pHead != 0 ) {
- struct Line* ptmp = pfile->pHead;
- pfile->pHead = pfile->pHead->next;
- free( ptmp );
- }
- }
- void write( struct MyFile* pfile, const char* file_name ) {
- FILE * pf = fopen( file_name, "w" );
- struct Line* pline = pfile->pHead->next;
- while( pline ) {
- fprintf( pf, "%s\n", pline->content );
- pline = pline->next;
- }
- fclose( pf );
- }
- void delete_line( struct MyFile* pfile, const char* line_content ) {
- struct Line* pline = pfile->pHead->next;
- struct Line* next = pline->next;
- int n;
- while( next ) {
- if( (n = strcmp( line_content, next->content )) == 0 ) {
- pline->next = next->next;
- free(next);
- break;
- }
- pline = next;
- next = next->next;
- }
- }
复制代码 先建立一个文件C:/data.txt内容可以如下:
aaaa
bbbb
cccc
dddd
eeee
执行后删除cccc那行 |
|