0

Coding for file handling. I cannot find the .txt file on my desktop. I am using MAC OS

void upload(){
    FILE *fp;
    int i;
    fp = fopen("StudentRecord.txt","w+");
    if (fp==NULL){
        printf("File Error!\n");
        system("pause");
    }
    else {
        for (i=0;i<=L.last;i++)
            fprintf(fp,"%s %d %d %d\n",L.st[i].name,L.st[i].q1,L.st[i].q2,L.st[i].q3);
    }
    fclose(fp);
}
void download(){
    FILE *fp;
    REC x;
    fp = fopen("StudentRecord.txt","r+");
    if (fp==NULL){
        printf("File error!\n");
        system("pause");
    }
    else{
        while(!feof(fp)){
            fscanf(fp,"%s %d %d %d \n",x.name,&x.q1,&x.q2,&x.q3);
            add(x);
        }
        fclose(fp);
    }
}

File extension .txt should be available in the folder where my main.c is located.

the busybee
  • 10,755
  • 3
  • 13
  • 30
xtie83
  • 1
  • 1
  • 1
    The filename is searched in the user's working directory, not the directory containing the program. – Barmar Nov 11 '22 at 01:47
  • @AllanWind I've never heard of that function. The standard Unix function is `getcwd()`. – Barmar Nov 11 '22 at 02:07
  • @Barmar sorry I am still new to MAC OS.. any idea where I can find the working directory? – xtie83 Nov 11 '22 at 02:36
  • 3
    Obligatory: [Why is “while( !feof(file) )” always wrong?](https://stackoverflow.com/q/5431941/2505965) – Oka Nov 11 '22 at 03:40
  • One possible solution is to configure Xcode to copy that text-file from your project's source-directory to the build output directory when it does a build, see here: https://stackoverflow.com/questions/9295043/xcode-4-c-project-add-file-to-build-directory - I'm not an Xcode user myself but I assume it's possible to configure it to _not_ overwrite the file if it already exists and/or has been modified-since the last build so you don't lose any changes your program made to it. – Dai Nov 11 '22 at 03:47
  • Another possibility is setting-up a symlink from your build output directory back to the original file: https://apple.stackexchange.com/questions/115646/how-can-i-create-a-symbolic-link-in-terminal – Dai Nov 11 '22 at 03:49
  • Are you running it in Xcode? Maybe the working directory is somewhere else (_ie_ in the bowels of Xcode build folder, which is by default not at all connected with your code)? On Xcode 12.4, go to edit scheme, Run, Options, Working Directory, Use Custom Working Directory: `$(SRCROOT)` (or `~/Desktop`). You can set all this up and create a reasonable template `.xcodeproj` in a locked folder. – Neil Nov 11 '22 at 04:39
  • @xtie83 When you're in Terminal, use `pwd` to find your working directory. It's normally your home directory, `/Users/yourusername`. Copy the text file to your directory. – Barmar Nov 11 '22 at 15:37

0 Answers0