您应该在这里检查几件事。它可能仍然无法达到您的预期,但它会避免您遇到的错误。
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.
}
}
}
请记住,在此之后,string
可能仍为 NULL。有关更多信息,请参见“fgets”。