我对 c 字符串的 fopen() 有一些问题
I have some problems with fopen() for c-string
我有一个存储为 C 字符串的文件名。我需要打开文件并计算其中的行数。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main() {
char str[] = "myfile.txt";
FILE* file = fopen(str, "r");
int counter = 0, ch = 0;
while (EOF != (ch = fgetc(file)))
if (ch == '\n')
++counter;
fclose(file);
printf("%d", counter);
return 0;
}
如果我使用 fopen("myfile.txt", "r")
insted,evrething 工作得很好。如何使其与 c 字符串文件名一起使用。
请use string.c_str()
int main() {
string path = "myfile.txt";
FILE* file = fopen(path.c_str(), "r");
int counter = 0, ch = 0;
while (EOF != (ch = fgetc(file)))
if (ch == '\n')
++counter;
fclose(file);
printf("%d", counter);
return 0;
}
我有一个存储为 C 字符串的文件名。我需要打开文件并计算其中的行数。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main() {
char str[] = "myfile.txt";
FILE* file = fopen(str, "r");
int counter = 0, ch = 0;
while (EOF != (ch = fgetc(file)))
if (ch == '\n')
++counter;
fclose(file);
printf("%d", counter);
return 0;
}
如果我使用 fopen("myfile.txt", "r")
insted,evrething 工作得很好。如何使其与 c 字符串文件名一起使用。
请use string.c_str()
int main() {
string path = "myfile.txt";
FILE* file = fopen(path.c_str(), "r");
int counter = 0, ch = 0;
while (EOF != (ch = fgetc(file)))
if (ch == '\n')
++counter;
fclose(file);
printf("%d", counter);
return 0;
}