通过stat()函数传递字符串

时间:2011-05-19 11:56:19

标签: c++

我有以下代码:

#include <stdio.h>       // For printf()
#include <sys/stat.h>   // For struct stat and stat()

struct stat stResult;

if(stat("Filename.txt", &stResult) == 0)
{
      // We have File Attributes
      // stResult.st_size is the size in bytes (I believe)
      // It also contains some other information you can lookup if you feel like it
printf("Filesize: %i", stResult.st_size);
}
else
{
      // We couldn't open the file
printf("Couldn't get file attributes...");
}

现在。如何通过stat()传递我自己的字符串?喜欢这个

string myStr = "MyFile.txt";
stat(myStr, &stResult)

2 个答案:

答案 0 :(得分:7)

如果您正在谈论C ++ std :: string,您可能想要使用

string myStr = "MyFile.txt";
stat(myStr.c_str(), &stResult)

所以使用字符串对象的c_str()成员函数来获取C字符串表示。

答案 1 :(得分:3)

使用c_str()成员函数。

myStr.c_str()

http://www.cplusplus.com/reference/string/string/c_str/

相关问题