如何在C中逐行读取HTTP文件

时间:2016-05-07 07:13:40

标签: c http

我想从互联网上的纯文本文件中取出,并逐行阅读。与您使用fgets()逐行读取文件的方式类似。我不想下载该文件。我知道如果你使用read()函数,你可以指定接收多少字节并逐行手动读取文件。我只是想知道是否有任何方法可以自动执行此操作。谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

我必须做很多事情,并写下以下小功能来帮助。只需拨打 FILE * wwwpopen(),* fp = wwwpopen(“http://wherever.com/whatever.html”,“r”); ,然后像往常一样使用 fp 来阅读。你喜欢什么方式。完成后,只需 pclose(fp)。这是小函数(注意:如果wget不在你的默认路径上,那么在你的系统上用wget的完整路径替换下面的wget [256]初始化),

/* ==========================================================================
 * Function:    wwwpopen ( char *url, char *mode )
 * Purpose:     popen("wget -O - url",mode)
 * --------------------------------------------------------------------------
 * Arguments:   url (I)     char * containing null-terminated string
 *                          with url to be opened
 *              mode (I)    char * containing null-terminated string
 *                          that should always be "r"
 *                          (this arg ignored, always "r"; just there for
 *                          consistency with fopen/popen calling sequence)
 * Returns:     ( FILE * )  file pointer to popen()'ed url file
 *                          or NULL for any error.
 * --------------------------------------------------------------------------
 * Notes:     o pclose(fileptr) yourself when finished reading file
 * ======================================================================= */
/* --- entry point --- */
FILE    *wwwpopen ( char *url, char *mode ) {
/* --- Allocations and Declarations --- */
FILE    *fileptr = NULL;        /* file ptr returned to caller */
char    defaultmode[16] = "r",  /* default mode, always used */
        wgetargs[16] = "-O -",  /* command-line args for wget */
        wget[256] = "wget",     /* replace by path to wget, if any */
        command[512];           /* constructed wget command */
/* --- Check input --- */
mode = defaultmode;             /* force popen() mode, must be "r" */
if ( url != NULL ) {            /* url supplied */
  /* --- popen() file --- */
  sprintf(command,"%s %s %s",   /* construct wget args url */
      wget,                     /* path to wget program */
      wgetargs,                 /* command-line args for wget */
      url);                     /* and url to be wgotten */
  fileptr = popen(command,mode); } /* popen() url (mode better be "r")*/
return ( fileptr );             /* back to caller with file ptr */
} /* --- end-of-function wwwpopen() --- */