如何从c程序中的任何目录加载文件

时间:2010-10-25 05:53:31

标签: c

我想更改下面的代码,使inwash文件能够从任何目录加载,而不是从tech_projects环境变量加载。

  /**Get projects directory from environment variable****************/
 strcpy(pjects.arr, getenv("Tech_Projects"));

  pjects.arr[strlen(pjects.arr)] = '\0';

  if (strcmp(inwashfile.arr, "null") != 0)
  {
    for (d=2;d<inwashfile.len;d++)
    {
      tempfile.arr[d-2] = inwashfile.arr[d];
    }      
    memset(inwashfile.arr, '\0', 255);    

    strcpy(inwashfile.arr, pjects.arr);
    strcat(inwashfile.arr, tempfile.arr);

    inwashfile.len = strlen(inwashfile.arr);
    inwashfile.arr[inwashfile.len] = '\0';
    do_wash[0] = 'T';
  }
  else
  {
    do_wash[0] = 'F';
  }
printf("3\n");
  do_wash[1] = '\0';

2 个答案:

答案 0 :(得分:0)

 /**Get projects directory from environment variable****************/
 /* You need to replace this line with wherever you want to get the
    file name from. Either request it from the user, pull it from a
    configuration file or read it from the command line */
 strcpy(pjects.arr, getenv("Tech_Projects"));

  /* this line does absolutely nothing. strlen() relies on the string
     already being null-terminated */
  pjects.arr[strlen(pjects.arr)] = '\0';

  if (strcmp(inwashfile.arr, "null") != 0)
  {
    for (d=2;d<inwashfile.len;d++)
    {
      tempfile.arr[d-2] = inwashfile.arr[d];
    }      
    memset(inwashfile.arr, '\0', 255);    

    strcpy(inwashfile.arr, pjects.arr);
    strcat(inwashfile.arr, tempfile.arr);

    inwashfile.len = strlen(inwashfile.arr);
    inwashfile.arr[inwashfile.len] = '\0';
    do_wash[0] = 'T';
  }
  else
  {
    do_wash[0] = 'F';
  }
printf("3\n");
  do_wash[1] = '\0';

答案 1 :(得分:0)

可能是

strcpy(pjects.arr, argv[ 1 ] );

并且命名目录可以从命令行传递,例如

$ myprogram /user/foo