我有一个基本的.txt文件,可能包含完全采用此格式的未知数量的数据,我需要在' ='之后提取第二部分。标识符。例如:
variable1=Hello
variable2=How
variable3=Are
variable4=You?
我需要提取"你好" "如何" "是"和#34;你?"单独并将它们存储到一个数组中(删除/忽略变量名称)并能够单独调用每个单词。我在C中这样做,这就是我现在拥有的。
#include <stdio.h>
#include <string.h>
int main()
{
char*result;
char copy[256];
FILE * filePtr;
filePtr = fopen("testfile.txt", "r+");
strcpy(copy, "testfile.txt");
while(fgets(copy, 256, filePtr)!= NULL)
{
result = strchr(copy, '=');
result = strtok(NULL, "=");
printf("%s",result);
if(result != 0)
{
*result = 0;
}
result = strtok(copy, "=");
}
return 0;
}
我当前的输出是
(null)How
Are
You?
答案 0 :(得分:1)
strtok
,使用strchr
就足够了。copy
缓冲区。"%r+"
打开文件。以下是更正后的版本:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char *words[20];
int n = 0;
char *result;
char copy[256];
FILE *filePtr;
filePtr = fopen("testfile.txt", "r");
while (fgets(copy, 256, filePtr) != NULL) {
copy[strcspn(copy, "\n")] = '\0'; /* strip the \n if present */
result = strchr(copy, '=');
if (result != NULL) {
words[n++] = strdup(result + 1);
printf("%s ", result + 1);
}
}
printf("\n");
fclose(filePtr);
return 0;
}
请注意在\n
copy
fgets()
之前删除copy[strcspn(copy, "\n")] = '\0';
末尾的尾部fgets()
。即使\n
在缓冲区结束之前或文件结束之前没有看到strcspn
,它仍然有效。 copy
count返回\n
中不在第二个参数中的字符数,因此它返回没有words
的行的长度。
将单词收集到指向字符串的数组malloc
中。每个单词都被strdup
函数复制到由strdup
分配的内存中。 _strdup
不是标准C的一部分,而是Posix的一部分,可能存在于您的环境中,可能写成strdup
。
另请注意,您还应该测试无法打开文件,无法在20
中分配内存,还要处理超过int main(void) {
char word1[20], word2[20], word3[20], word4[20];
FILE *filePtr;
filePtr = fopen("testfile.txt", "r");
if (fscanf(filePtr,
"%*[^=]=%19[^\n]%*[^=]=%19[^\n]%*[^=]=%19[^\n]%*[^=]=%19[^\n]",
word1, word2, word3, word4) == 4) {
printf("%s %s %s %s\n", word1, word2, word3, word4);
// perform whatever task with the arrays
} else {
printf("parse failed\n");
}
fclose(filePtr);
return 0;
}
个字符串......
如果有一组固定的单词并且您只想剥离初始部分,则可以使用更简单的硬编码方法:
{{1}}