2015-03-06 1 views
-2

У меня проблема. Я установил строку «Отсутствует» для всех учащихся в файле. Тем не менее, я хочу заменить «Отсутствует» на «настоящее», когда вводится правильный идентификатор, назначенный ученику. Другими словами, «Отсутствует» будет изменяться только на «Присутствие» для определенного человека за раз. Я не уверен, как это реализовать, и я прошу, чтобы кто-то помог. Заранее спасибо.Как заменить строку определенного лица в файле

UPDATE :: ====

#include <stdio.h> 
#include <conio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <stdbool.h> 
#include <time.h> 
#include <errno.h> 


typedef struct record { 
    char *fname; 
    char *lname; 
    int code; 
    char *stat; 
} information; 


int main (void) { 
    int i; 
    char ffname[28], flname[28], ans, status[15]; 

    int fID, j, id_, x; 
    FILE *kfile, *ufile; 
    x = 0; 
    j = 0; 
    i = 0; 



    char buf[150]; 
    time_t curtime; 
    struct tm* loc_time; 
    information array[100]; 

    printf("   **********Attendance Recording System**********\n"); 
    printf("         MENU      \n"); 
//Getting current time of system 
    curtime = time (NULL); 
// Converting current time to local time 
    loc_time = localtime (&curtime); 
    strftime (buf,150, "%I:%M %p.\n", loc_time); 


//prints error message if file cannot be found within the system 

    if ((kfile = fopen("information.txt", "r")) == NULL) //If the file path is incorrect, an error message is displayed 
    { 
     fprintf(stderr, "Error while opening file (%d: %s)\n",errno, strerror(errno)); //Error message that will be displayed if file path is incorrect 

     return; 
    } 

    //while the file is opened and not at the end, the strings are stored into variables which forms an array of strings 
    for (x = 0; x < 200; x++) { 
     if (fscanf(kfile, "%s %s %d", ffname, flname, &fID) != 3) //Reads the contents of the file 
     break; 
     array[x].fname = strdup(ffname); 
     array[x].lname = strdup(flname); 
     array[x].code = fID; 
    } 
    fclose(kfile); 

    ufile= fopen("update.txt","w"); 
     strcpy(status, "Absent"); 
    fprintf(ufile,"First Name  Last Name  ID  Status  Time Arrived\n"); 
    for (i = 0; i < x; i++) { 
    fprintf(ufile,"%-15s%-14s%2d%12s ",(array[i].fname), (array[i].lname), (array[i].code), status); 
    fprintf(ufile,"%16s",(buf)); 

} 
fclose(ufile); 

while(j < x){ 
printf("Enter you ID: "); 
scanf("%d", &id_); 

strcpy(status, "Absent"); 
bool isPresentInFile = false; 
for(i=0; i<x; i++) 
{ 
    if(array[x].code == id_) 
    { 
     printf(" %s %s?", array[x].fname, array[x].lname); 
     isPresentInFile = true; 
     break; 
    } 
} 

if(isPresentInFile) 
{ 
    strcpy(status, "present"); 
} 

j++; 
} 

fprintf(ufile,"First Name  Last Name  ID  Status  Time Arrived\n"); 
    for (i = 0; i < x; i++) { 
    fprintf(ufile,"%-15s%-14s%2d%12s ",(array[i].fname), (array[i].lname), (array[i].code), status); 
    fprintf(ufile,"%16s",(buf)); 

} 
    fclose(ufile); 


getch(); 
return 0; 
} 

UPDATE # 3

#include <stdio.h> 
#include <conio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <stdbool.h> 
#include <time.h> 
#include <errno.h> 


typedef struct record { 
    char *fname; 
    char *lname; 
    int code; 

} information; 


int main (void) { 
    int i; 
    char ffname[28], flname[28], ans, ans1, status[15]; 

    int fID, j, id_, x; 
    FILE *kfile, *ufile; 
    x = 0; 
    j = 0; 
    i = 0; 



    char buf[150]; 
    time_t curtime; 
    struct tm* loc_time; 
    information array[100]; 

    printf("   **********Attendance Recording System**********\n"); 
    printf("         MENU      \n"); 
//Getting current time of system 
    curtime = time (NULL); 
// Converting current time to local time 
    loc_time = localtime (&curtime); 
    strftime (buf,150, "%I:%M %p.\n", loc_time); 


//prints error message if file cannot be found within the system 

    if ((kfile = fopen("information.txt", "r")) == NULL) //If the file path is incorrect, an error message is displayed 
    { 
     fprintf(stderr, "Error while opening file (%d: %s)\n",errno, strerror(errno)); //Error message that will be displayed if file path is incorrect 

     return; 
    } 

    //while the file is opened and not at the end, the strings are stored into variables which forms an array of strings 
    for (x = 0; x < 200; x++) { 
     if (fscanf(kfile, "%s %s %d", ffname, flname, &fID) != 3) //Reads the contents of the file 
     break; 
     array[x].fname = strdup(ffname); 
     array[x].lname = strdup(flname); 
     array[x].code = fID; 
    } 
    fclose(kfile); 



while(j < x){ 
    Next: 
printf("Enter you ID: "); 
scanf("%d", &id_); 

strcpy(status, "Absent"); 
bool isPresentInFile = false; 
for(i=0; i<x; i++) 
{ 
    if(array[i].code == id_) 
    { 

     printf("Are you %s %s?", array[i].fname, array[i].lname); 
     printf("\n"); 
     printf("[y/n only]: "); 
     scanf(" %c", &ans); 


     isPresentInFile = true; 
     break; 
    }//end of if statement 
}//end of for loop 

if(isPresentInFile) 
{ 
    strcpy(status, "present"); 
}//end of if statement 
switch (ans){ 
    case 'y': 
     ufile= fopen("update.txt","w"); 

    fprintf(ufile,"First Name  Last Name  ID  Status  Time Arrived\n"); 
    for (i = 0; i < x; i++) { 
    fprintf(ufile,"%-15s%-14s%2d%12s ",(array[i].fname), (array[i].lname), (array[i].code), status); 
    fprintf(ufile,"%16s",(buf)); 


}//end of for loop 
fclose(ufile); 
printf("Continue?\n"); 
printf("[y/n]: "); 
scanf(" %c", &ans1); 

if(ans1 == 'y'){ 
    break; 
}//end of if statements 
    else if (ans1 == 'n'){ 
     exit(EXIT_SUCCESS); 
    }//end of else statement to check if ans1 is equal to 'n' 

    case 'n': 
     goto Next; 
     break; 
    default: 
     printf("invalid entry. Try again"); 
}//end of switch case statememt 
j++; 
}//end of while 





getch(); 
return 0; 
} 
+0

Сообщите нам ваш код! – CinCout

+0

Под 'правильным идентификатором', что вы имеете в виду? Есть ли определение правильного идентификатора? 'должно ли значение быть в определенном диапазоне? –

ответ

1

Из Вашего вопроса, я не получил, когда именно вы хотите изменить status от "Absent" к "present".

Но вы можете использовать тот же метод strcpy(), чтобы перезаписать переменную status.

... 
strcpy(status, "Absent"); 
if(//condition) 
{ 
    strcpy(status, "present"); 
} 

UPDATE 1:

После прочтения комментария, я понял, что вы предложите пользователь ввести идентификатор. И если он совпадает с идентификатором, присутствующим в файле, вам необходимо обновить status до "present", а затем записать в новый файл.

я могу придумать что-то вроде этого:

... 
// read from file 
..... 
int ID; 
printf("Enter you ID: "); 
scanf("%d", &ID); 

strcpy(status, "Absent"); 
bool isPresentInFile = false; 
for(int i=0; i<x; ++i) 
{ 
    if(array[x].code == ID) 
    { 
     isPresentInFile = true; 
     break; 
    } 
} 

if(isPresentInFile) 
{ 
    strcpy(status, "present"); 
} 

... 
// write to file 
..... 

UPDATE 2: После прочтения обновленного вопроса, я заметил, что вы пишете в файл в конце! Но каждый раз переписывая переменную статуса. Таким образом, вы в конечном итоге писать либо "Absent" или "Present" для всех записей в файле (! Обратите внимание, что это относится к последнему кандидату, который входит в его ID)

Чтобы избежать этого, выполните одно из следующих действий:

  1. Напишите в файл, как только вы узнаете статус кандидата.

    while(j < x) 
    { 
    printf("Enter you ID: "); 
    scanf("%d", &id_); 
    
    strcpy(status, "Absent"); 
    bool isPresentInFile = false; 
    for(i=0; i<x; i++) 
    { 
        if(array[x].code == id_) 
        { 
         printf(" %s %s?", array[x].fname, array[x].lname); 
         isPresentInFile = true; 
         break; 
        } 
    } 
    
    if(isPresentInFile) 
    { 
        strcpy(status, "present"); 
    } 
    
    // write to file here 
    
    j++; 
    } 
    
  2. также поле, называемое status в структуре information. По умолчанию держите его "Absent" для всех кандидатов. Затем сделайте это "Present" только для тех, кто вводит свои идентификаторы. Наконец, напишите его в файл.

+0

Я хочу изменить его после того, как студент войдет в свой идентификатор, и он совпадает с их идентификатором в файле. Таким образом, по фрагменту, который вы только что отправили, будет ли он переписываться «Отсутствует» для этого конкретного ученика? или он будет перезаписывать каждый «Отсутствует» в файле? –

+0

@SantoshA По правильному идентификатору я имею в виду, что программа предложит пользователю ввести свой ID, и он будет искать файл для того же ID. Если он соответствует любому в файле, он изменит значение «Отсутствует» на «Подарок» –

+0

@Kkkkkkkkkkkk: Не забудьте добавить это к вопросу, чтобы получить более конкретный ответ. –

Смежные вопросы