在 c 中标记输入文件

Tokenizing an input file in c

我正在尝试实现一个简单的程序来分隔文件中的每个单词。这是我第一次使用 strtok(),所以我试图创建一些简单的东西来查看它是如何工作的。但是,我无法让代码正常工作。

代码如下:

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

char* tokenize(char *tempPhrase);

int main (void)
{

    FILE *in;
    char file_name[] = "test1.txt";
    char buffer[100];
    char *tokens = malloc (100 * sizeof (char));
    int i;

    chdir("./DataFiles");
    if (( in = fopen(file_name, "r")) == NULL)
    {
            printf("Can't open %s for reading.\n", file_name);
            return 0;
    }

    fgets(buffer, 100, in);
    printf("%s\n", buffer);
    *tokens = tokenize (buffer);

    for (i = 0; tokens[i] != NULL; i++)
    {
            printf("%s\n", tokens[i]);
    }

    return 0;
 }


 char*  tokenize(char *tempPhrase)

 {

    char *search = " ";
    char *tempArray = malloc (20000 * sizeof (char));

    int i = 0;
    tempArray[i] = strtok(tempPhrase, search);

    while(tempArray[i] != NULL)
    {
            i++;
            tempArray[i] = strtok(tempPhrase, search);
    }


return tempArray;
}

我在尝试编译时得到以下 errors/warnings:

fopen.c: In function ‘main’:
fopen.c:28: warning: comparison between pointer and integer
fopen.c:30: warning: format ‘%s’ expects type ‘char *’, but argument 2 has type ‘int’
fopen.c: In function ‘tokenize’:
fopen.c:45: warning: assignment makes integer from pointer without a cast
fopen.c:47: warning: comparison between pointer and integer
fopen.c:50: warning: assignment makes integer from pointer without a cast

为什么 strtok() 函数会使 tempArray 成为整数?这在整个程序中引起了各种各样的问题,我无法弄清楚。

我发现您的代码存在一些问题:

char tokens = malloc (100 * sizeof (char));

这一行你 malloc 不是指针,至少应该是 char* tokens

那应该去掉几个

fopen.c:28: error: subscripted value is neither array nor pointer

警告

您在 tokenize 函数中再次执行了同样的操作。

然后 malloc 应该始终跟在 free 调用之后,以释放您使用的内存。否则你有泄漏。

所以在某个地方你需要在完成后调用 free(tokens)。您的第二个 malloc 电话也是如此。

根据 strtok 文档,如果您希望它从停止的地方继续标记化,您应该使用第一个参数 NULL 调用 strtok

所以tempArray[i] = strtok(tempPhrase, search);真的应该是这样的

tempArray[i] = strtok(NULL, search);,以便它继续标记您最初传递给它的字符串。

你的 tempArray 初始化应该更像这样

char** tempArray = malloc(10 * sizeof(char*)); //初始化第一个数组

你需要char**的原因是因为你想要一个字符串数组,而C中的字符串用char*表示,所以现在你需要一个指向[=数组的指针27=] 即 char**

这些只是我能看到的一些问题,没有实际尝试编译您的代码。

Here is a version of your program that compiles