【问题标题】:Loop in C,Problems with LoopC语言中的循环,循环的问题
【发布时间】:2016-04-18 19:25:17
【问题描述】:

我有这部分代码,我想一直执行。但是当我围绕它创建一个while 循环(或任何循环)时 - 它只是执行(因此循环由于某种原因不起作用)。如何为这段代码创建一个恒定循环?

int main(void)
{
    int temp = 0;
    while (temp != 1) {       //here is the loop i was trying

        CURL *curl;
        CURLcode res;
        FILE *hd_src;
        struct stat file_info;
        curl_off_t fsize;

        struct curl_slist *headerlist = NULL;
        static const char buf_1[] = "RNFR " UPLOAD_FILE_AS;
        static const char buf_2[] = "RNTO " RENAME_FILE_TO;

        if (stat(LOCAL_FILE, &file_info)) {
            printf("Couldnt open '%s': %s\n", LOCAL_FILE, strerror(errno));
            return 1;
        }
        fsize = (curl_off_t)file_info.st_size;

        printf("Local file size: %" CURL_FORMAT_CURL_OFF_T " bytes.\n", fsize);

        hd_src = fopen(LOCAL_FILE, "rb");

        curl_global_init(CURL_GLOBAL_ALL);

        curl = curl_easy_init();
        if (curl) {
    
            headerlist = curl_slist_append(headerlist, buf_1);
            headerlist = curl_slist_append(headerlist, buf_2);
    
            curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);    
            curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L); 
            curl_easy_setopt(curl, CURLOPT_URL, REMOTE_URL);
            curl_easy_setopt(curl, CURLOPT_POSTQUOTE, headerlist);
            curl_easy_setopt(curl, CURLOPT_READDATA, hd_src);
            curl_easy_setopt(curl, CURLOPT_INFILESIZE_LARGE,
                (curl_off_t)fsize);
            
            res = curl_easy_perform(curl);
            
            if (res != CURLE_OK)

                fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));

            curl_slist_free_all(headerlist);

            curl_easy_cleanup(curl);
        }
        fclose(hd_src); 

        curl_global_cleanup();
    }

    return 0;
}

【问题讨论】:

  • 返回前是否显示“无法打开...”?

标签: c loops


【解决方案1】:

我通常会做的是:

while(true)   // In C you can also write 'while(1)'
{
    // Your code
}

要确保您的循环实际上是“循环”,只需创建一个始终递增的变量 i,然后将其打印出来:

int i = 0;
while(true)
{
    i++;
    print("Loop iteration: " + i);
    // Your code here.
}

如果由于变量“i”是整数而导致打印语句出错,请查看此链接: Converting int to string in c

编辑

如果您的程序在没有更多详细信息的情况下直接停止,则您可能遇到了错误。我会做的是:

int i = 0;
while(true)
{
    i++;
    // Some code here
    print("I got to this point.");
    // Some more code
    print("Yet another milestone reached.");
    // Some more code
    print("The end of loop: " + i);
}

至少你得到了一些输出。并且您可以找出错误的可能位置。

祝你好运:-)

【讨论】:

  • 干得好!如果您还有其他问题,请随时提问。我很乐意帮助你。如果真的对您有帮助,请按“接受答案”按钮。那真是太好了;-)
猜你喜欢
  • 2015-03-09
  • 1970-01-01
  • 1970-01-01
  • 2020-09-07
  • 2013-08-24
  • 1970-01-01
  • 2012-01-05
  • 2021-03-06
相关资源
最近更新 更多