Home > database >  Translating a function from Python to C
Translating a function from Python to C

Time:11-27

Im struggling with a certain function in Python, it's nothing complicated but i need to "translate" it to C with very limited prior knowledge.

def BuildCommandList(commands : list, filepath : str):

    commands.clear()

    try:
        file = open(filepath, 'r')
    except FileNotFoundError:
        return False

    for line in file:
        line = line.replace('\n','')

        if len(line) != 0:      
            line = line.split()             
            commands.append(line)
    file.close()

    return True

Above is the function in Python, below is my current attempt at the same thing in C

bool BuildCommandList(std::vector<std::vector<std::string>>& commandList, std::string filepath)
{
    
    std::ifstream test(filepath);
    test.open(filepath);

    if (test.is_open())
    {
        std::string line, text;
        while (std::getline(test, line))
        {
            if (!line.empty() || line.find_first_not_of(' ') == std::string::npos)
            {
                text  = line   "\n";
            }

            if (len(line) != 0); //Obviusly doesn't work
            {

            }
        }
    }

    else
    {
        return false;
    }


    return true;
}

Any and all help is appreciated

CodePudding user response:

The natural equivalent to Python's len is std::size, or equivalently the size member of std::string. However you might prefer the empty member of std::string for your condition.

You then need to split your string. This can be done with a std::stringstream and std::istream_iterator to construct a std::vector<std::string> (overload 5) in place.

Note that getline doesn't include the \n, so you don't need to modify line before splitting it.

bool BuildCommandList(std::vector<std::vector<std::string>>& commandList, std::string filepath)
{
    commandList.clear();

    std::ifstream test(filepath);
    if (!test)
    {
        return false;
    }

    for (std::string line; std::getline(test, line); )
    {
        if (!line.empty())
        {
            using iterator = std::istream_iterator<std::string>;
            commandList.emplace_back(iterator{std::stringstream{line}}, iterator{});
        }
    }

    return true;
}
  • Related