簡體   English   中英

從C中的文件讀取並執行條件邏輯

[英]Read from file in C and execute conditional logic

我是編程新手,對於如何實現這個想法有一些疑問。

我正在尋找一個用戶輸入他們的名字/數字字符串,如果他們的名字在列表中,然后執行一串命令。 我不確定如何隱含這一點,但是經過一番摸索,我才提出了以下代碼:

#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,執行/調用另一個函數)

提前致謝!

嘗試這個:

#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;

   }

fopen只是打開一個文件進行讀取和/或寫入,要讀取文件的實際內容,您需要使用諸如fgetsfscanf等功能。

簡短的例子

#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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM