【发布时间】:2020-02-24 01:48:39
【问题描述】:
我必须编写一个文件处理代码,它将从用户接收到的字符串与存储在 C 文件中的 char 字符串进行比较。我从昨天开始尝试。我不知道该怎么做。我尝试了很多东西,但似乎没有任何效果。
//
// 2.c
// IFTM Exercises
//
// Created by Lelre Ferreira on 10/27/19.
// Copyright © 2019 Lelre Ferreira. All rights reserved.
//
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, const char * argv[]){
FILE *file = fopen("file.txt", "w");
char text[] = "hi hi hi hi hi hi"; //string to be allocated into the file
char c, userInput[] = "hi"; // simulates the user input
int i = 0, count = 0;
if (file == NULL) {
printf("Failure to create file.\n");
exit(1);
} else {
for (i = 0; i < strlen(text); i++) {
printf("Inserting: [%c]\n", text[i]);
fputc(text[i], file);
}
printf("All done.\n");
}
fclose(file);
fopen("file.txt", "r");
while ((c = fgetc(file) != EOF)){
fscanf(file, "%s", text);
if (strcmp(userInput, text) == 0) {
count++;
}
}
fclose(file);
printf("Many times present: %d\n", count);
return 0;
}
我的问题是......文件中字符串的每个单词之间的空格,因为我必须检查是否有另一个单词开始,例如......(嗨嗨)......我想过使用类似的东西这在我的代码中,但我没有工作。
while ((c = fgetc(file) != EOF)){ // While the end of the file does not happen keep running.
if ((c = fgetc(file) != ' ')) { //If an blank space is found... I does not make any sense actually. I'm desesperated.
strcmp(userInput, text){
count++
}
}
}
【问题讨论】:
-
不相关,
c应该是int。只是说。与您的问题相关,我认为没有理由在您的阅读器循环中使用fgetc逻辑进行搜索。while (fscanf(file, "%s", text) == 1)似乎更合适,在循环本身中丢失了fscanf调用。
标签: c function file file-handling