[英]retrieving words from a single line in a file using fgets and strtok
我具有下面的函數,該函數從文件中讀取單詞,並使用fgets和strtok輸出每個單詞,其中文件中的單詞由換行符分隔:
word1
word2
word3
我正在嘗試模仿功能,其中文件中的單詞在單行中僅由空格分開:
word1 word2 word3
但是,我似乎只能在將strtok char更改為“”並嘗試讀取一行時獲得第一個單詞。 我不確定我缺少什么。
#include <string.h>
#include <malloc.h>
int readLines;
char *output[255];
char *filename = "commands.txt";
char fileRead(const char *filename, char *output[255])
{
int count = 0;
char input[255];
char *line;
FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Cannot open file: %s\n", filename);
} else {
while(count < 255 && fgets(input, sizeof(input), file)) {
line = strtok(input, "\n");
if (line) {
output[count++] = strdup(line); /* Store replica */
}
}
fclose(file);
}
return count;
}
char *strdup(const char *str)
{
char *ret = malloc(strlen(str)+1);
if (ret) {
strcpy(ret, str);
}
return ret;
}
int main(int argc, char *argv[])
{
readLines = fileRead(filename, output);
/* read from array and pass into flag function */
for (int x = 0; x < readLines; ++x) {
printf("%s\n", output[x]);
free(output[x]);
}
return 0;
}
如果我理解您的問題-您想將文件中包含在一行中的所有單詞( 標記 )分開,那么您使用的strtok
錯誤。 在您的代碼中,您有line = strtok(input, "\\n");
分隔符是換行符 。 如果要分隔用空格隔開的單詞,則還需要在定界符中包含一個space
,例如char *delim = " \\n";
此外,在第一次調用strtok
,使用緩沖區的變量名(或指向緩沖區的指針)保存要標記化的文本。 對於所有剩余的strtok
調用(例如,單詞2, 3, 4...
),請在其位置使用NULL
並檢查返回值。
總結一下示例,您可以執行以下操作:
#include <stdio.h>
#include <string.h>
#define MAXC 255
int main (int argc, char **argv) {
char buf[MAXC] = "",
*delim = " \n";
FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;
if (!fp) { /* validate file open for reading */
fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
return 1;
}
if (!fgets (buf, MAXC, fp)) { /* read one line from file */
fprintf (stderr, "error: file read failed.\n");
return 1;
}
/* tokenize line with strtok */
for (char *p = strtok (buf, delim); p; p = strtok (NULL, delim))
printf ("%s\n", p);
if (fp != stdin) fclose (fp); /* close file if not stdin */
return 0;
}
輸入文件示例
$ cat dat/strtok.dat
my dog has fleas
使用/輸出示例
$ ./bin/strtokoneline <dat/strtok.dat
my
dog
has
fleas
如果我誤解了,請發表評論,我們很樂意為您提供進一步的幫助。 如果您對答案還有其他疑問,請提出。
如果您更喜歡將strtok
循環寫成while
循環而不是for
(看起來更容易),則可以執行以下操作:
char buf[MAXC] = "",
*p = buf,
*delim = " \n";
...
p = strtok (buf, delim); /* get first token (word) */
while (p) {
printf ("%s\n", p);
p = strtok (NULL, delim); /* get remaining tokens */
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.