文件在CURL中打开

时间:2015-09-18 13:35:03

标签: c curl libcurl

我正在使用libcurl编写一个c程序。我正在连接到在localhost上运行的服务器,然后将此检索到的数据从服务器保存在文件中。当我使用" file.txt"这样的文件名时,我可以写和读我的文件。但是当我尝试更改文件名并将其附加当前数据和时间时,我收到错误"将接收到的数据写入磁盘/应用程序"失败。

以下是我的代码:

`    int main(int argc, char *argv[])
    { 
      float freq;
      CURL *curl;
      CURLcode res;
      FILE *fp, *file_r;
      char *buffer;
      buffer = malloc (100000);
      char url[1024], name[20];
      char *filename;
      filename = (char *) malloc (100);
      if (filename == NULL)
      {
        printf("Error in memory allocation");
      }`

  /* Store the data retireved from webpage in a file and name the file  with current date and time */
      time_t  now;
      time (&now);
      struct tm *t = localtime (&now);
      strftime (name, 20, "%d %m %Y %H:%M:%S", t);
  //  printf ("%s\n", name);

      filename[0] ='\0'; // Ensure the memory is an emtpy string;
      strcat (filename, "file_new_");
      strcat (filename, name);
      strcat (filename, ".txt");
      printf ("%s\n", filename);
      printf("enter your input frequency value\n");
      scanf("%f", &freq);
      sprintf(url, "http://127.0.0.1:8080/?action=update_frequency&update_frequency=%f",freq);

    /* In windows, this will init the winsock stuff */
      curl_global_init(CURL_GLOBAL_ALL);

    /* get a curl handle */
      curl = curl_easy_init();
      if(curl)
      {
          curl_easy_setopt(curl, CURLOPT_URL, "http://127.0.0.1:8080");

          /* Now specify the username & pwd */

          curl_easy_setopt(curl, CURLOPT_USERPWD, "admin:12345");

          /* Specify the web request */

          curl_easy_setopt(curl, CURLOPT_URL, url);

          /* Storing the received data in a file */

          fp = fopen (filename, "w+");

          curl_easy_setopt (curl, CURLOPT_WRITEDATA, fp);

    /* Perform the request, res will get the return code */

          res = curl_easy_perform(curl);

        /* Check for errors */
          if (res != CURLE_OK)
          {
            fprintf(stderr, "curl_easy_perform() failed: %s\n",curl_easy_strerror(res));
          }

          fclose (fp);

    /* To read the return msg from server after performing a request */

          file_r= fopen (filename, "r");
          fseek (file_r, SEEK_SET, 0);
          while (fgets (buffer, 100000, file_r)!=NULL)
          {
            ;
          }
          printf( "%s\n", buffer);
          fclose (file_r);
          }

        /* always cleanup */
          curl_easy_cleanup(curl);

          curl_global_cleanup();
          return 0;
        }

如果有人有任何想法,会有很大的帮助。 非常感谢

1 个答案:

答案 0 :(得分:1)

您不能在Windows上的文件名中使用字符{{1}},这就是它无法保存的原因。将分隔符更改为其他内容。