从C中读取文件并执行条件逻辑

时间:2014-04-20 22:29:57

标签: c keil

我是编程新手,对如何实现这个想法有一些疑问。

我希望让用户输入他们的姓名/数字字符串,如果他们的名字在列表中,则执行一串命令。我不确定如何表达这一点,但通过一些gogle-ing,我能够提出这个代码:

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


   int main(void)
   {

      char userName[10];

      printf("\n\n\n\nPlease enter your name: ");
      scanf_s("%s",userName);     // userName should be verified/found inside the results.dat file

      FILE *fp;

      fp = fopen("results.dat", "r");

      if (fp == NULL) {
         printf("I couldn't open results.dat for writing.\n");
         exit(0);
      }

      if (fp == John) {
            //Dispence squence of pills for John
      }

      if (fp == Mary) {
            //Dispence squence of pills for Mary
      }



      return 0;

   }

我认为我没有正确使用if语句。我该怎么做:

if(fp == john中的内容,执行/调用另一个函数)

提前致谢!

2 个答案:

答案 0 :(得分:2)

试试这个:

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

   int main(void)
   {

      char userName[10];
      char names[20];
      printf("\n\n\n\nPlease enter your name: ");
      scanf("%s",userName);     // userName should be verified/found inside the results.dat file

      FILE *fp;

      fp = fopen("results.dat", "r");

      if (fp == NULL) {
         printf("I couldn't open results.dat for writing.\n");
         exit(0);
      }

      while(fgets(names, 20, fp)) // fgets reads a line from the file
      {
        names[strlen(names)-1] = '\0'; // but it leaves the newline character "\n" , so the strings won't match
        if(strcmp(names, userName) == 0) // if the value returned by strcmp is zero then string match
        {
            printf("Match found\n");
        }
      }

      return 0;

   }

答案 1 :(得分:1)

fopen只是打开一个文件进行阅读和/或写作,以阅读您需要使用fgetsfscanf等功能的文件的实际内容。< / p>

简短的例子

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

int main (int argc, char* argv[])
{
   char name[64];
   char buffer[64];

   printf ("Please enter your name: ");

   file = fopen ("results.dat", "rw");
   if (!file) {
      printf ("Results.dat could not be opened.\n");
      exit(-1);
   }

   if ( fgets (buffer, 64, file)) {
      if (strcmp (buffer, "john")) {
         printf ("Contents of file is john\n");
      }
   }

   return 0;
}