我有一个运行良好的程序,直到在使用之前关闭文件为止std::getline()
。该close(fileTest)
行使while循环永远重复,而无需询问用户输入。getline()
即使在第一个循环上,它也只会跳过。
我花了大约2个小时试图弄清楚这一点,所以我了解所有有关缓冲区和cin>>
行为的知识。我最终在getline()
通话之前注释掉了台词,并了解了发生的情况。
显然,我遇到了很多有关输入缓冲区的重复问题,并且我知道文件的工作方式相似,但是我不明白为什么getline()
当我明确地从中请求数据时搞砸了,cin
或者为什么关闭文件触发了它。
知道为什么会发生这种情况或解决方法(不只是让文件永久打开)吗?
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
//#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <iostream>
#include <string.h>
#include <limits>
using namespace std;
char *fileName;
struct stat fileStatus;
int main(int arc, char **argv)
{
fileName = argv[1];
string menuChoice = "1";
//TODO: remove this. Testing only
fileName = (char *)"test";
//print message for no args
if (fileName == NULL)
{
printf("NO file selected\nUsage: fileutil <filename>\n\n");
}
//Make sure we can actually open the file
int fileTest;
if (fileTest = (open(fileName, O_RDONLY)) < 0)
{
perror("Failed to open file");
return (EXIT_FAILURE);
}
close(fileTest); //THIS MESSES UP cin IF NOT COMMENTED OUT?????
//main menu loop
while (true)
{
//display the menu and handle options
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::getline(cin, menuChoice);
//view file contents
if (menuChoice == "1")
{
}
//display file info
else if (menuChoice == "2")
{
}
//change file permissions
else if (menuChoice == "3")
{
}
//copy file
else if (menuChoice == "4")
{
}
//exit
else if (menuChoice == "5")
{
printf("Thank you. Exiting program...\n\n");
return (0);
}
//handle invalid responses
else
printf("Invalid response\n\n");
}
return 0;
} //end main
在fileTest = (open(fileName, O_RDONLY)) < 0
比较,因为它具有较高的优先级分配之前进行。因此,fileTest
将不保存open
调用结果,而是保存比较结果,该结果可能与标准输入/输出句柄之一(通常为0、1、2)相同。因此,随后close
将关闭标准输入,而open
丢失的返回句柄将丢失。open
还应将-1的结果进行检查。
因此,经验法则是永远不要使用赋值运算符的结果:
auto const fileTest{::open(fileName, O_RDONLY)};
if (-1 == fileTest)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句