使用fstream无法访问.txt文件的技术求助
C++读取TXT文件失败的排查与解决
常见问题及解决方向
1. 路径匹配错误
直接写"donneesProduits.txt"属于相对路径,程序会在当前工作目录(通常是编译生成的可执行文件所在的Debug/Release文件夹)查找文件,而非你存放源代码的目录。
- 解决方式:
- 把
donneesProduits.txt复制到可执行文件所在目录; - 改用绝对路径,比如
"C:/Users/你的用户名/Documents/donneesProduits.txt"(注意用斜杠/或双反斜杠\\)。
- 把
2. 文件格式或编码异常
即使你认为文件没问题,也需要确认:
- 每行的分隔符确实是
##,没有多余空格、制表符或隐藏字符; - 可以在
getline循环内添加调试代码,查看实际读取的内容:while (getline(fichierProduits, ligne)) { cout << "当前读取行:" << ligne << endl; // 后续分割代码... }
3. 代码逻辑的潜在隐患
数组越界风险
produits tabProduits[tailleTab];是固定长度数组,如果文件行数超过tailleTab会直接崩溃。建议改用动态容器:
#include <vector> // ... vector<produits> tabProduits; // 读取完字段后 produits temp; temp.ID = IDp; temp.produit = produitp; // 其他字段赋值... tabProduits.push_back(temp);
分割逻辑未做错误处理
如果某一行的##数量不足7个,ligne.find(delimiteur)会返回string::npos,导致substr和erase操作出错。需添加判断:
size_t pos = ligne.find(delimiteur); if (pos == string::npos) { cout << "行格式错误,跳过:" << ligne << endl; continue; } IDp = ligne.substr(0, pos); ligne.erase(0, pos + delimiteur.length());
类型不匹配问题
如果produits结构体中Qte、prixu是数值类型(如int、float),直接赋值字符串会报错,需转换:
tabProduits[cptProd].Qte = stoi(Qtep); tabProduits[cptProd].prixu = stof(prixup);
4. 系统权限限制
- 不要把文件放在系统保护目录(如C盘根目录、Program Files);
- Windows系统可尝试右键以管理员身份运行程序。
调试辅助:打印具体错误信息
在文件打开失败的分支中添加错误详情,定位具体原因:
#include <cerrno> #include <cstring> // ... if (!fichierProduits) { cout << "无法访问文件:" << strerror(errno) << endl; system("pause"); exit(1); }
内容的提问来源于stack exchange,提问作者Benjkf5
相关产品推荐
相关产品推荐

