[C/C++]ファイルの読み込み方法
3614 ワード
1つ目:fgetc
2つ目:fread
第三:フォルダが存在するかどうかを判断する
windows:
Filenameはファイルパスでもフォルダパスでも絶対パスまたは相対パスを使用できます
_AccessModeは検証するファイルアクセス権、読み取り可能、書き込み可能、実行可能、およびフォルダが存在するかどうかの4つの権限を表し、Filenameがフォルダを表す場合はフォルダが存在するかどうかのみを問い合わせることができます.
_AccessMode:
ヘッダファイルhには以下の定義がある.
第四:ファイル名とファイルパスの取得
第五:ファイルの書き込み
int fopentest()
{
FILE *file;
char c;
file = fopen("./test.txt", "r");
if (file == NULL) {
printf(" ");
return -1;
}
while(1)
{
c = fgetc(file);
if (feof(file)) {
break;
}
printf("%c", c);
}
fclose(file);
return 0;
}
2つ目:fread
#include
#include
int main() {
FILE *fp = fopen("./test.txt", "r");
if (fp == NULL) {
return -1;
}
char buf[1024];
while(1) {
//
memset(buf, 0, sizeof(buf));
int fr = fread(buf, sizeof(char), sizeof(buf), fp);
if (fr <= 0) {
break;
}
printf("%s
", buf);
}
fclose(fp);
return 0;
}
第三:フォルダが存在するかどうかを判断する
windows:
#include
string folder = "d:/pictures";
if (_access(folder.c_str(), 0) == -1)
{
cout << " " << endl;
return -1;
}
cout << " :" << folder << endl;
linux: #include
int access(const char* _Filename, int _AccessMode)
ファイルまたはフォルダへのアクセス権を決定する機能です.指定したアクセス権が有効である場合、関数は0を返します.そうでない場合は-1を返します.Filenameはファイルパスでもフォルダパスでも絶対パスまたは相対パスを使用できます
_AccessModeは検証するファイルアクセス権、読み取り可能、書き込み可能、実行可能、およびフォルダが存在するかどうかの4つの権限を表し、Filenameがフォルダを表す場合はフォルダが存在するかどうかのみを問い合わせることができます.
_AccessMode:
ヘッダファイルhには以下の定義がある.
#define R_OK 4 /* Test for read permission. */
#define W_OK 2 /* Test for write permission. */
#define X_OK 1 /* Test for execute permission. */
#define F_OK 0 /* Test for existence. */
:
R_OK
W_OK
X_OK
F_OK
:
00
02
04
06
参考文書:http://blog.csdn.net/u012005313/article/details/50688257 第四:ファイル名とファイルパスの取得
// string::find_last_of
#include // std::cout
#include // std::string
#include // std::size_t
void SplitFilename (const std::string& str)
{
std::cout << "Splitting: " << str << '
';
std::size_t found = str.find_last_of("/\\");
std::cout << " path: " << str.substr(0,found) << '
';
std::cout << " file: " << str.substr(found+1) << '
';
}
int main ()
{
std::string str1 ("/usr/bin/man");
std::string str2 ("c:\\windows\\winhelp.exe");
SplitFilename (str1);
SplitFilename (str2);
return 0;
}
Splitting: /usr/bin/man
path: /usr/bin
file: man
Splitting: c:\windows\winhelp.exe
path: c:\windows
file: winhelp.exe
第五:ファイルの書き込み
bool WriteLog(const char *log) {
FILE *pf;
char filepath[128] = { 0 };
//
if (!strcmp(log, "") || !log) {
printf(" ");
return false;
}
//
if (_access("data", 0) != 0) {
if (_mkdir("data") != 0) {
Sleep(1000);
if (_mkdir("data") != 0) {
printf("
");
return 0; //
}
}
printf("
");
}
//
snprintf(filepath, 128, "%s\\%s", "data", "mylog.log");
//
pf = fopen(filepath, "a+");
if (!pf) return false;
fwrite(log, strlen(log), sizeof(char), pf);
fclose(pf);
return true;
}