简体   繁体   中英

reading In a file in C program cannot find file specified

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);
}

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

time_logs/time.log is the name of the file, which you want to open. Specify the full path.

Eg “C:\\myfiles\\time_logs\\time.log”

The time.log file should be available in your Specified Directory

#include <stdio.h>

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

   /* opening file for reading */
   fp = fopen("C:\\myfiles\\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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM