获取文件并操作文件大小

时间:2013-02-14 12:18:28

标签: c string

我的算法是

1。扫描目录中的所有文件(使用C完成)

2。在循环中获取当前文件的文件大小(使用C完成)

3. 如果它小于8 kb做某事并将下一个立即文件名存储在一个数组中(好像在C中不支持关联数组)

我已经在PHP中完成了这项工作,但由于不可预见的事件,它现在需要用C语言编写。我确实经历了很多关于C的教程,说实话,我低估了我认为需要获得的时间。基础知识。

经过相当长的一段时间后,我设法找到了一个列出目录中文件的代码。

#include <dirent.h> 
#include <stdio.h>
#include <conio.h>

int main(void)
{ 
  char path = "D:\\ffmpeg\\bin\\frames\\"; 
  DIR           *d;
  struct dirent *dir;
  char test;
  d = opendir("D:\\ffmpeg\\bin\\frames\\");
  if (d)
  {
    while ((dir = readdir(d)) != NULL)
    {      
       printf("%s\n", dir->d_name);
    }

    closedir(d);
  }
  getchar();
  return(0);
}

现在很明显,循环中的当前文件由dir->d_name表示。我遇到的问题是将其添加到"D:\\ffmpeg\\bin\\frames\\",以便路径变为"D:\\ffmpeg\\bin\\frames\\somename.jpg"

这将帮助我获取文件的直接路径。一旦我得到它,我将有所需的数据转移到第2步。我现在面临的问题是字符串连接。我试过了strcat()但是没有成功。

基本上我正在寻找的是

while ((dir = readdir(d)) != NULL)
{      
   // merge "path" and "dir->d_name" to get something similar like
   // "D:\\ffmpeg\\bin\\frames\\somename.jpg"
}

任何帮助,建议?

2 个答案:

答案 0 :(得分:1)

strcat()仅在您的字符串有足够的空间来容纳结果时有效,并且它将使目标无效以便后续遍历您的循环。

我会建议使用asprintf()函数,尽管它有一个小警告;它将分配你负责返回的内存。

while ((dir = readdir(d)) != NULL)
{
   char *fullname;
   asprintf(&fullname, "%s%s", "D:\\ffmpeg\\bin\\frames\\", dir->d_name);
   printf("%s\n", fullname);

   // now do things with `fullname`

   free(fullname); // return the memory allocation at the end of the loop
}

答案 1 :(得分:1)

普通C中推荐的解决方案是snprintf

char buf[MAX_PATH];
snprintf(buf, sizeof(buf), "%s%s", path, dir->d_name);

请勿使用strcat()strncat()

如果您使用的是MSVC,那么您的C实施已过期24年,并且snprintf()不可用。您的选择是:

  1. 使用_snprintf()然后buf[sizeof(buf)-1] = '\0';作为解决方法。

  2. 使用C ++和std::string

  3. 使用Cygwin。