【问题标题】:Returning char * from int function without use of pointer?从 int 函数返回 char * 而不使用指针?
【发布时间】:2017-04-21 07:25:04
【问题描述】:

我有一个函数,它从给定文件中读取,查找给定关键字,返回一个键值,该键值由给定字符串与单词分隔。 我的函数的返回值目前是 char *,据​​我了解,这对于错误处理来说是低于标准的。 另一方面,我不想摆弄一个指针来存储值。至少在这种情况下。

有没有办法只通过函数返回字符串值,同时返回成功/失败的 int 值?

我的字符 * 代码:

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

/*!
 * @brief Loads the config file and returns value of requested parameter search
 * @param char *file - Config file to search in
 * @param char *seperator - Seperator to identify keyword and keyvalue 
 * @param char *search - Requested parameter to look for
 * @return char * - Value of found keyword or error if search failed
*/

int confin(char *file, char *seperator, char *search)
{
    FILE *conf;
    char *buffer;
    char *output;
    char line[256];

    char *returnerror = "Error!";


    if((conf = fopen(file, "r")) == NULL)                                   // Try to open file from path, return error if failed
    {
        fprintf(stderr, "Could not open config file \"%s\"!\n", file);
        return returnerror;
    }

    while (fgets(line, sizeof(line), conf) != NULL)                         // Read lines of file until the end is reached
    {
        buffer = strtok(line, seperator);                                   // Search for first appearance of seperator in line;
        if((strcmp(buffer,search)) == 0)                                    // If keyword is found,
        {
            buffer = strtok(NULL, seperator);                               // buffer the keyvalue,
            output = malloc(sizeof(buffer));
            strcpy(output, buffer);                                         // copy it into the output string,
            output[strcspn(output, "\n")] = 0;                              // replace the "\n" char from the end with terminating 0
            fclose(conf);
            return output;                                                  // and return the value of output.        
        }
    }

    fprintf(stderr, "Could not find config keyword \"%s\"!\n", search);
    fclose(conf);
    return returnerror;

}


int main ()
{
    printf("%s\n",confin("test.conf","=","test"));
}

我试过下面的代码,但是返回的值是(null)

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

/*!
 * @brief Loads the config file and returns value of requested parameter search
 * @param char *file - Config file to search in
 * @param char *seperator - Seperator to identify keyword and keyvalue 
 * @param char *search - Requested parameter to look for
 * @return int - 0 on success, 1 on failure 
*/

int confin(char *file, char *seperator, char *search, char *value)
{
    FILE *conf;

    char *output;
    char *buffer;
    char line[256];


    if((conf = fopen(file, "r")) == NULL)                                   // Try to open file from path, return error if failed
    {
        fprintf(stderr, "Could not open config file \"%s\"!\n", file);
        return 1;
    }

    while (fgets(line, sizeof(line), conf) != NULL)                         // Read lines of file until the end is reached
    {
        buffer = strtok(line, seperator);                                   // Search for first appearance of seperator in line;
        if((strcmp(buffer,search)) == 0)                                    // If keyword is found,
        {
            buffer = strtok(NULL, seperator);                               // buffer the keyvalue,
            output = malloc(sizeof(buffer));
            strcpy(output, buffer);                                         // copy it into the output string,
            output[strcspn(output, "\n")] = 0;                              // replace the "\n" char from the end with terminating 0.
            strcpy(value,output);                                           // Store the new value in my return value     
            fclose(conf);
            free (output);
            return 0;                                                       // and return the value of output.        
        }
    }

    fprintf(stderr, "Could not find config keyword \"%s\"!\n", search);
    fclose(conf);
    return 1;

}


int main ()
{
    char value[256] = "\0";
    printf("%s\n",confin("test.conf","=","test",value));
}

希望这件事能尽快解决。即使这意味着我必须在最后使用指针方法。提前致谢!

【问题讨论】:

  • 一种方法是创建一个包含char*int 的结构;然后让你的函数返回它。这是 C 中的常见做法,但是如果您想返回 char*,只需将 char** 作为返回参数传递。
  • C 中的另一种方法是在调用函数时传递的指针中返回 char* 结果。然后函数的返回值将是一个 int 来指示它是否成功。
  • 我的建议是在你的函数中使用一些 printf 语句来跟踪正在发生的事情。当涉及到许多标准库函数时,C 可能会很有趣。它们可能不像你想象的那样工作。
  • 当您没有找到字符串值时返回NULL 似乎是合理的。此外,output = malloc(sizeof(buffer)); 只分配 4 或 8 个字节(指针的大小)。

标签: c string pointers


【解决方案1】:

变化:

int main ()
{
    char value[256] = "\0";
    printf("%s\n",confin("test.conf","=","test",value));
}

到:

int main ()
{
    char value[256] = "\0";
    int retval = confin("test.conf","=","test",value);
    if(retval)
        // some error handling
    printf("%s\n", value);
}

您所做的是调用confin,它将字符串值分配给value,但您尝试从该函数打印返回的int(作为字符串)而不是value

您也可以只返回char*,如果配置文件中不存在密钥,则返回NULL。这是“没有这样的键”类型错误的简单案例。在这种情况下,您只需检查 confin 是否返回 NULL。

【讨论】:

    【解决方案2】:

    你已经得到了一些很好的答案,但我很惊讶这里没有人提到 errno。 (https://en.wikipedia.org/wiki/Errno.h)

    Errno 是 C 中管理错误的一种常用方法。例如,您可以在发生错误的函数中自己设置 errno 并返回 NULL。这将通知调用函数出现问题。

    【讨论】:

      猜你喜欢
      • 2016-06-10
      • 2015-03-03
      • 2021-02-14
      • 1970-01-01
      • 2015-06-08
      • 1970-01-01
      • 1970-01-01
      • 2021-08-14
      • 2015-01-02
      相关资源
      最近更新 更多