[英]C++ write to file
I have a program which writes to text file. 我有一个写入文本文件的程序。
Example in my textfile: 我的文本文件中的示例:
4
QA131 100 100 100 100
QA132 100 100 100 100
QA133 100 100 100 100
QA134 100 100 100 100
I want to write a new line which store the record and the 4 will turn into 5. 我想写一个存储记录的新行,4将变为5。
What is the method used to write to the file? 用于写入文件的方法是什么?
Here is my code: 这是我的代码:
void inputRecord()
{
Product product[101];
char FILENAME[20];
cout<<"Enter the file you want to open: ";
cin>>FILENAME;
ifstream read(FILENAME);
if (read.is_open())
{
while(read.good())
{
read>>product[0].line;
for(int i =0;i< product[0].line;i++)
{
read >>product[i].PartNumber
>>product[i].initialQuantity
>>product[i].quantitySold
>>product[i].minQuantity
>>product[i].price;
}
product[0].line+=1;
}
read.close();
}
ofstream write(FILENAME);
write<<product[0].line << endl;
for(int i =0;i< product[0].line;i++)
{
write << product[i].PartNumber << '\t'
<< product[i].initialQuantity << '\t'
<< product[i].quantitySold << '\t'
<< product[i].minQuantity << '\t'
<< product[i].price << '\t' << endl;
}
write.close();
cout << "Inventory added successfully!" << endl;
system("pause");
system("CLS");
}
I cannot write the item to the file. 我无法将该项目写入文件。
you could just use fseek to solve your problem. 你可以用fseek来解决你的问题。
Here's a really simple example based this C++ reference example 这是一个基于这个C ++参考示例的简单示例
#include<cstdio>
int main(void) {
FILE * pFile;
pFile = fopen ( "test.txt" , "wb" );
fprintf(pFile,"00000\n"); // watch spacing
for (int i=1; i<11; i++) {
fprintf (pFile, "%d. This line a line of stuff.\n",i);
}
fseek(pFile , 0 , SEEK_SET );
fprintf(pFile,"10 \n");
fclose(pFile);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.