Home > Mobile >  write to file specified by the user
write to file specified by the user

Time:11-09

readFromFile() function is used at the start of the program.

When the user writes a name of a file the program should read data from that file if the file exists, if the file with that name does not exist it should keep the name entered by the user and before closing the program write it to that file with the writeToFile() function.

The issue is in fp=fopen(a,"w"); the writeTofile() function does not recognize a, so it does not know what name the user entered at the begining of the program. My thinking is that since I have FILE *fp in both it should recognize that "a". But it does not I cannot figure out how to do it.

to summ it up. writeTofile() function needs to know what filename user wrote in readFromFile().

void readFromFile(Car reg[], int *pNrOfCars){
   
    FILE *fp;
    char a[100];
    printf("filename: ");
    fscanf(stdin,"%s",a);
    strcat(a,".txt");
    fp=fopen(a,"r");

    if(fp!=NULL){
        char model[WORDLENGTH];
        int year,milage;  
        while(fscanf(fp,"%s %d %d",model,&year,&milage)==3){
        reg[*pNrOfCars]=createCar(model,year,milage); 
        (*pNrOfCars)  ;  
        }
      fclose(fp); 
    }     
}
void writeToFile(Car reg[], int nrOfCars){

    FILE *fp;
    fp=fopen(a,"w");
    if(fp!=NULL){
        for (int i = 0; i < nrOfCars; i  ){
        fprintf(fp,"%s %d %d\n", reg[i].model, reg[i].year, reg[i].milage);
        }
        fclose(fp);
    }
}

CodePudding user response:

Do this part in a separate function:

    char a[100];
    printf("filename: ");
    fscanf(stdin,"%s",a);
    strcat(a,".txt");

And then pass a to both function readFromFile and function writeToFile.

CodePudding user response:

The variable a is inside the readFromFile() function, and thus not visible from the outside.

One "solution" is to make it global, i.e. define it outside all functions:

char a[100];

void readFromFile(Car reg[], int *pNrOfCars){
  /* ... */
}

then it would be visible from inside any function, but global variables are generally not a good idea since they are messy and make it harder to understand a program.

It's better to pass the filename to the function, by adding an argument:

void readFromFile(Car reg[], int *pNrOfCars, const char *filename) {
  /* ... use filename instead of a ... */
}

then move the code that gets the filename to the main() function, since reading the name is something that is not specific to reading it should not be done inside the file:

int main(void)
{
   char fname[100];
   printf("filename: ");
   fscanf(stdin,"%s", fname);
   strcat(fname, ".txt");  
   
   readFromFile(..., fname);
   /* ... process data ... */
   writeToFile(..., fname);

   return 0;
}

I skipped some details, marked by "...".

  •  Tags:  
  • c
  • Related