c 读文件

c 读文件

#include <stdio.h>
#include 
<stdlib.h>
#include 
<string.h>

#define szBUF 30000



int main(int argc, char * argv[])
{
    
char filename[szBUF]={0};
    
char buf[szBUF]={0};
    
char a[szBUF];

    
char *need_find_start = "<RoomType>";
    
int lens_start = strlen(need_find_start);
    
char *need_find_end = "</RoomType>";
    
int lens_end = strlen(need_find_end);


    
char *head  = NULL;
    
char *end = NULL;

    
//    int r = 0;
    
//    int b=0;
    FILE * f = 0;
    
if(argc < 2) {
        printf(
"please input the file name:");
        gets(filename);
    }
    
else
        strcpy(filename, argv[
1]);
    
//end if
    f = fopen(filename, "r");
    
if(!f) {
        printf(
"file %s open fault!\n", filename);
        
return 0;
    }
//end if



    
while(fgets(buf,30000,f) != NULL)
    {
        head 
= strstr(buf, need_find_start);
        
if(head != NULL)
        {
            end 
= strstr(buf, need_find_end);
            
if(end != NULL)
            {
                
long long int lens = (long long int)(end) - (long long int)(head) - lens_start;
                
char *strings = (char*)malloc(lens + 1);
                strncpy(strings, head 
+ lens_start, lens);
                printf(
"123\n");
                printf(
"%s\n\n", strings);
            }
            
else
            {
                
while(fgets(buf,30000,f) != NULL)
                {
                    end 
= strstr(buf, need_find_end);
                    
if(end != NULL)
                    {
                        
long long int lens = (long long int)(end) - (long long int)(head) - lens_start;
                        
char *strings = (char*)malloc(lens + 1);
                        strncpy(strings, head 
+ lens_start, lens);
                        printf(
"123\n");
                        printf(
"%s\n\n", strings);
                    }
                }
            }
        }

        
/*
           head = strstr(buf, "<RoomType>");
           int room_lens = strlen("<RoomType>");
           if(head != NULL)
           {
           end = strstr(head, "</RoomType>" );
           if(end != NULL)
           {
           long long int lens = (long long int)(end) - (long long int)(head) - room_lens;
           strings = (char*)malloc(lens + 1);
           strncpy(strings, head + room_lens, lens);
           }
           }
           
*/
    }

    fclose(f);
    
return 0;
}

  

posted @ 2011-07-12 18:14  wangkangluo1  阅读(346)  评论(0编辑  收藏  举报