我正在尝试编写一个程序,该程序在运行时需要几个参数来将文本附加到文件中。
该程序在运行时产生分段错误。这是代码:
int main(int argc, char* argv[])
{
//error checking
if (argc < 1 || argc > 4) {
cout << "Usage: -c(optional - clear file contents) <Filename>, message to write" << endl;
exit(EXIT_FAILURE);
}
char* filename[64];
char* message[256];
//set variables to command arguments depending if -c option is specificed
if (argc == 4) {
strcpy(*filename, argv[2]);
strcpy(*message, argv[3]);
} else {
strcpy(*filename, argv[1]);
strcpy(*message, argv[2]);
}
int fd; //file descriptor
fd = open(*filename, O_RDWR | O_CREAT, 00000); //open file if it doesn't exist then create one
fchmod(fd, 00000);
return 0;
}
我仍然是一个初学者,我在理解 c 字符串时遇到了巨大的麻烦。char* 和 char[] 和 char* [] 有什么区别?
更新:
代码仍然会引发分段错误,这是我修改后的代码:
using std::cout;
using std::endl;
int main(int argc, char* argv[])
{
//error checking
if (argc < 1 || argc > 4) {
cout << "Usage: -c(optional - clear file contents) <Filename>, message to write" << endl;
exit(EXIT_FAILURE);
}
char filename[64];
char message[256];
//set variables to command arguments depending if -c option is specificed
if (argc == 4)
{
strncpy(filename, argv[2], 64);
strncpy(message, argv[3], 256);
}
else
{
strncpy(filename, argv[1], 64);
strncpy(message, argv[2], 256);
}
int fd; //file descriptor
fd = open(filename, O_RDWR | O_CREAT, 00000); //open file if it doesn't exist then create one
fchmod(fd, 00000);
return 0;
}