2013-12-17 3 views
1

사용자가 switch 문에 입력 한 "패킷"구조의 사용자 입력 데이터를 저장할 수있는 저장 시스템을 구현하려고합니다. 입력 된 각 레코드는 일반 텍스트로 구분 된 단일 파일에 저장됩니다. 또한 사용자에게 파일의 이름을 묻는 메시지를 표시해야합니다. 그러면 프로그램은 파일에 저장 된 레코드 수를 나타내야합니다. 마지막으로 저장 파일에 대한 이름을 입력하지 않으면 주 메뉴로 돌아갑니다.데이터 구조를 텍스트 파일로 저장

하단의 무효 저장 기능에서 볼 수 있듯이이 저장 시스템을 구현하려고했지만 프로그램을 실행하고 S를 선택하여 파일에 레코드를 저장하면 이름을 입력 한 후 충돌이 발생합니다 파일명 그래서 누군가가 이것으로 나를 도울 수 있다면 그것은 좋을 것입니다.

UPDATE

디버거를 통해 프로그램을 실행 한 후 내가 얻을 다음과 같은 오류

UPDATE

고정 도청 오류가 있지만 프로그램이 충돌 곳의 데이터 것 텍스트 파일의 파일 이름을 입력 역시 구원 받아야한다.

#include <stdio.h>   //library including standard input and output functions 
#include <stdlib.h>   //library including exit and system functions used below 
#include <string.h>   //library including string functions used 



struct packet{ 
    int source; 
    int destination; 
    int type;    // Varibles for the structure 
    int port; 
    char data[50]; 
    char * filename; 
}; 

void save(int, struct packet*); //function to save the records stored to a file 

int main() 
{ 
struct packet s[50];   //Array for structure input 
char choice; 
int NetworkPacket = 0, ii = 0; 
int recordCount = 0; 
struct packet *records; 
struct packet *temp; 
records = malloc(sizeof(struct packet)); 

     do{ 

    system("cls"); 
    puts("Please enter an option:\n"); 
    puts("'A' Add a packet:\n"); 
    puts("'D' to Display the Packet List:\n");     // The Menu system 
    puts("'S' to Save the Packets to a file:\n"); 
    puts("'C' to Clear the list of current saved packets:\n"); 
    puts(" or X to exit the program...\n"); 

    //wait for user input 
    scanf("%c", &choice); //take the first char of user input and assing the value to 
          //the variable choice using the address of (&) the variable 
    if(choice == '\n')  //check to see that the character is not \n left over from the 
     scanf("%c", &choice); //previous choice made, if it is then we need to scan the input again 

    switch (choice) 
        { 
         case 'A': system("cls"); //clear the screen 

         if(NetworkPacket==50) 
           { 
            printf("No more network packets can be added"); // if statement giving the limit of 50 packets allowed to be added 
            getch();  // User must press a key to continue 
            continue; 
           } 
         else{ 
           printf("\n****Adding a packet*****\n"); 
           printf("Where is the packet from?\n"); 
           scanf("%i", &s[NetworkPacket].source); 
           printf("Where is the packet going?\n"); 
           scanf("%i", &s[NetworkPacket].destination); 
           printf("What type is the packet?\n"); 
           scanf("%i", &s[NetworkPacket].type);      // collecting the data of the packet inputted by the user 
           printf("What is the packet's port?\n"); 
           scanf("%i", &s[NetworkPacket].port); 
           printf("Enter up to 50 characters of data.\n"); 
           scanf("%s", s[NetworkPacket].data); 
           NetworkPacket++; 
          }break; 

         case 'D': system("cls"); //clear the screen 
           printf("\nDisplaying Infomation\n"); 

           if(NetworkPacket==0)   // if statement stating to the user no records are shown if none are avalible 
            { 
             printf("no records yet, Please press any key to revert back to the main menu\n"); 
             getch();  // User must press a key to continue 
             continue; 
            } 
           else{ 
           for(ii = 0; ii < NetworkPacket; ii++) 
             { // adds a 1 onto the NetworkPacket counter keeping a tally on the number of records stored. 
              printf("\nSource: %d", s[ii].source); 
              printf("\nDestination: %d", s[ii].destination); 
              printf("\nType : %d", s[ii].type);// if statement giving the limit of 50 packets allowed to be added 
              printf("\nPort : %d", s[ii].port); 
              printf("\nData: %s\n---\n", s[ii].data); 
             }getch(); 
            } break; 

         case 'S': 
          system("cls"); //clear the screen 
          save(NetworkPacket, records); //S was chosen so use the Save function 
         break;      //the while condition is True so break the switch and loop around 

         case 4: break; 
         case 5: break; 

         default:system("cls"); printf("%c is not an option\n Try again...\n", choice); // this message is shown if user doesn't input of one the case statment letters. 


         } 
         }while(choice!='X'); // exits the program 

         return 0; 

} 


void save(int rCount, struct packet *NetworkPacket){ 
    FILE *recordFile;     //file handle 
    char fileName[30] = { '\0'};  //string to store the file name 
    int i; 

    puts("Enter a filename to save the records :"); //ask the user for the filename 
    scanf("%s", fileName);       //store the filename: data input should be checked 
                //here in your program 

    //try and open the file for writing and react accordingly if there is a problem 
    if((recordFile = fopen(fileName,"w"))==NULL){ 
     printf("Couldn't open the file: %s\n",fileName); 
     exit(1); 
    } 
    else{ //the file opened so print the records array of packets to it 
     for(i=0;i<rCount;i++){ 
      fprintf(recordFile,"%04d %04d %04d %04d %s\n", 
        NetworkPacket[i].source, 
        NetworkPacket[i].destination, 
        NetworkPacket[i].type, 
        NetworkPacket[i].port, 
        NetworkPacket[i].port, 
        NetworkPacket[i].data); 
     } 
     fclose(recordFile); //close the file 
    } 

} 'S'일보다 더

+0

코드를 형식화하십시오. 읽기가 어렵습니다. 디버거를 사용하려고 했습니까? –

+0

예 디버거를 시험해 보았습니다. 줄 5 : 경고 : "struc packet"이 매개 변수 목록에 선언되었습니다. –

+0

휴식을 주셔서 감사합니다.하지만 분명히 그 문제가 있습니다. –

답변

2
case 'S': break; <---- you have a break just after the case definition try remove it 
    system("cls"); //clear th 

다른 경우? 및 조언을 scanf 대신 fgets 사용해야합니다.

+0

경고 : "struc packet"이 파라미터 목록 –

0

확인 내가 디버거 오류를 수정,하지만 난에 대한 파일 이름을 선택하라는 메시지가 있어요 때 주요 문제가있다하는 방법을 알아 낸 내 파일 저장, 프로그램은

line 5: warning: "struc packet" declared inside parameter list 

그래서이 내가 때문에 일어난 충돌 stc 패킷이 무엇인지를 먼저 밝히지 않고 함수에서 struc 패킷을 선언했습니다. 하지만 지금

line 22: warning: assignment makes integer from pointer without a cast 

고정되고 난에게 Struc 패킷 데이터로서 상기

line 89: warning: passing arg 2 of 'save' makes pointer from integer without a cast 

동일한 용액의 주소를 가리키는 실제 포인터를 제공함으로써이 문제를 해결.

코드를 업데이트합니다.

+0

안에 선언 된 경우 코드 ** 형식 **을 올바르게 업데이트 할 때 올바르게 읽을 수 있습니다. 올바른 형식의 코드는 유지 관리 및 디버그가 훨씬 쉽습니다. –

관련 문제