[英]Pointers, passing arguments to main, and segfaults
The three things mentioned in the title are somewhat new to me. 标题中提到的三件事对我来说有点新。 I am familiar with all of them conceptually but this is the first time I have tried to write my own program from scratch in C++ and it involves all three of these things. 我在概念上对它们都很熟悉,但这是我第一次尝试用C ++从头开始编写自己的程序,它涉及到所有这三个方面。 Here is the code: 这是代码:
int main(int argc, char *argv[])
{
FILE *dataFile;
char string [180];
dataFile = fopen(argv[1],"r");
fgets(string,180,dataFile);
fclose(dataFile);
}
It compiles fine, but when I execute using a simple input text file I get a segmentation fault. 它可以很好地编译,但是当我使用简单的输入文本文件执行时,出现了段错误。 I have searched multiple tutorials and I can't figure out why. 我搜索了多个教程,但不知道为什么。 Any help would be appreciated. 任何帮助,将不胜感激。
There are two likely causes of a segmentation fault in your code: 您的代码中有两种可能导致分段错误的原因:
argv[1]
does not exist, in which case attempting to access it may result in a segfault. argv[1]
不存在,在这种情况下尝试访问它可能会导致段错误。 Check if (argc > 1)
to avoid this problem. 检查if (argc > 1)
避免此问题。 fopen
does not successfully open the file, in which case attempting to read from the file ( fgets
) or fclose
it will cause a segmentation fault. fopen
无法成功打开文件,在这种情况下,尝试从文件( fgets
)或fclose
读取文件将导致分段错误。 Immediately after a call to fopen, you should check that the return value is not NULL
, eg if (dataFile == NULL)
. 在调用fopen之后,应立即检查返回值是否不是NULL
,例如if (dataFile == NULL)
。 There are a few things you should be checking here. 您应该在这里检查几件事。 It still may not do what you expect, but it will avoid the errors you're getting. 它仍然可能无法达到您的期望,但可以避免出现错误。
int main(int argc, char** argv)
{
if(argc > 1) // FIRST make sure that there are arguments, otherwise no point continuing.
{
FILE* dataFile = NULL; // Initialize your pointers as NULL.
const unsigned int SIZE = 180; // Try and use constants for buffers.
Use this variable again later, and if
something changes - it's only in one place.
char string[SIZE];
dataFile = fopen(argv[1], "r");
if(dataFile) // Make sure your file opened for reading.
{
fgets(string, SIZE, dataFile); // Process your file.
fclose(dataFile); // Close your file.
}
}
}
Remember that after this, string
may still be NULL. 请记住,在此之后, string
可能仍为NULL。 See 'fgets' for more information. 有关更多信息,请参见“ fgets”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.