Warm tip: This article is reproduced from serverfault.com, please click

reading In a file in C program cannot find file specified

发布于 2020-11-28 04:49:53

I'm new to C programing and was trying to get this simple program to run for reading in a file from a directory called "time_logs" that has the file that I want to read from called "time.log" I'm not entirely sure that I have the correct syntax for this but when I try to run this program in Visual Studio 2019 I get the message "Unable to start program C:programpath///.... The system cannot find the file specified"

I originally wrote this program In atom and then opened it with Visual studio, I'm guessing that I might not have some of the required files auto-created that would normally be there if I had created the program through Visual Studio, but I'm not sure. Any input would be helpful full thank you.

#include <stdio.h>

int main () {
   FILE *fp;
   char str[100];

   /* opening file for reading */
   fp = fopen("time_logs/time.log" , "r");
   if(fp == NULL) {
      perror("unable to open file");
      return(-1);
   }
   if( fgets (str, 100, fp)!=NULL ) {

      puts(str);
   }
   fclose(fp);

   return(0);
}

Questioner
YHapticY
Viewed
0
21.1k 2020-11-28 13:23:06

In regards to your question your code seems to work its just where you are referencing the file I believe.

you put fp = fopen("time_logs/time.log" , "r");

but I believe you want fp = fopen("./time_logs/time.log" , "r");

The ./ makes it so you are refrencing the relative project path then the folder containing the files and then finally the file.

Evan :D