我是 C/C++ 编程的新手,我正在努力提高我对文件 i/o 的理解。对于这个程序,我最初尝试在 C 中将 myFile 设为 typedef(这显然行不通),因此我转向了 C++ 中的类(这就是为什么没有代码使用 iostream 的原因)。
#include <stdio.h>
#include <stdlib.h>
// required myFile.file=fopen("path","mode");
// read from file: myFile.read(char* out);
// write to file: myFile.write(char* in);
class myFile {
public:
FILE *file;
void open(const char *path, const char *mode) {
file=fopen(path,mode);
}
/*void read(char *out) {
fread(out, sizeof(out[0]), sizeof(out)/sizeof(out[0]*sizeof(char)), file);
}*/
void write(char *in) {
fwrite(in, sizeof(in[0]), sizeof(in)/sizeof(in[0]), file);
printf("%i : %s\n",sizeof(in),in);
}
};
int main(){
myFile file1;
file1.open("/path/test.txt", "w+b");
char fileInput[]={"a b c Test a b c\n"};
file1.write(fileInput);
printf("%i : %s\n",sizeof(fileInput),fileInput);
//fwrite(fIn, sizeof(fIn[0]), sizeof(fIn)/sizeof(fIn[0]), file1.file);
//fprintf(file1.file,"a b c d Test a b c d\n");
fclose(file1.file);
return 0;
}
当我尝试将要写入文件 (fileInput) 的字符串传递给 file1.write() 时,它似乎可以工作,但它写入的文件仅包含 fileInput 的前 8 个字符。
出于调试目的放置 printf 以显示 write() 中 out 的大小和内容,以及传递给它的 fileInput:
8 : a b c Test a b c 18 : a b c Test a b c
很明显,out 比 fileInput 小,但包含相同的内容(?),这令人困惑,因为我假设 out 将被视为传递给 write() 的实际参数,因为 out 是指向 fileInput 的指针。
有什么方法可以让我解释为与 fileInput 完全相同,还是我的处理方式完全错误?
最佳答案
When I try pass the string I want to write to the file (fileInput) to file1.write(), it appears to work, but the file that it writes to only contains the first 8 characters of fileInput.
这是因为:
write(in, sizeof(in[0]), sizeof(in)/sizeof(in[0]), file);
如果我们也看一下函数头:
void write(char *in)
in
的类型为 char*。因此 sizeof(in)
将返回指针的大小(可能是 8)。 in[0]
的类型为 char
因此 sizeof(in[0])
将返回 1。
所以这一行将从输入中写入 8 个字符。
您需要做的是将字符串的大小作为参数传递。或者传递一个内置 size 方法的对象。我会使用 std::string 作为参数(或者 std::vector 取决于用法)。
void write(std::string const& in) {
fwrite(&in[0], 1, in.size(), file);
}
用法现在变成:
file1.write("hi there this is a message");
关于类中的 C++ 类参数与传递给类的参数不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20506641/