C从控制台打开文件

时间:2017-04-02 02:14:09

标签: c

我有一个简单的代码,它在读取模式下从hdd打开一个文件,但是代码中已经给出了文件的路径。我希望用户通过控制台手动提供文件名,路径和文件打开类型。我该怎么做?

#include<stdio.h> 

int main() { 
   FILE *fp; 
   fp = fopen("D:\\samplefile.txt","r");     
   if(fp != NULL) { 
      printf("File has been opened");         
      fclose(fp); 
   }     
   else printf("File not found"); 
   return 0; 
}   

2 个答案:

答案 0 :(得分:0)

// Use of function scanf is done here as an simple use. There are other ways also to get input from user
#include<stdio.h> 
int main()
{
  FILE *fp; 
  char filePath[100];
  printf("Enter Path name: ");
  scanf("%s", filePath);
  printf("value is %s",filePath);
   fp = fopen(filePath,"r");     
    if(fp != NULL) { 
      printf("File has been opened");         
      fclose(fp); 
   }     
   else printf("File not found"); 
   return 0; 
}

答案 1 :(得分:0)

#include <stdio.h>

int main()
{
  FILE *fp; 
  char filePath[100],filePermission[10];
  printf("Enter Path name: ");
  scanf("%s", filePath);
  printf("Enter file permission parameters: ");
  scanf("%s", filePermission);

   fp = fopen(filePath,filePermission);     
   if(fp != NULL) { 
      printf("File has been opened");         
      fclose(fp); 
   }     
   else printf("File not found"); 
   return 0; 

}