【发布时间】:2015-01-02 17:49:43
【问题描述】:
所以,我有这个:
order.txt
file.txt;10;21:21
file2.txt;3;20:00
file2.txt;30;22:20
file4.txt;3;10:00
我希望用户提供所需的行(1 到 3,取决于存在多少行),然后更改其内容。例如:
第 3 行
"文件名: file.txt"
"秒: 5"
"时间 HH:MM: 20:00"
输出/更改为 order.txt:
file.txt;10;21:21
file2.txt;3;20:20
file.txt;5;20:00
file4.txt;3;10:00
如您所见,第三行发生了变化。为此,我尝试了以下方法:
变量
FILE* orderFile;
FILE* contentFile;
char fileName[50];
char timeValue[10];
int seconds;
char orderNameFile[50];
char orderTimeFile[50];
int orderSecondsFile;
int count = 0;
int i = 0;
int line;
int position;
代码
/* This will show the content on it with the number of the line behind */
orderFile = fopen("order.txt","r+");
printf("\n");
while(fscanf(orderFile," %49[^;];%d; %49[^\n]",fileName,&seconds,timeValue) == 3)
{
i++;
printf("[%d] %s;%d;%s\n",i,fileName,seconds,timeValue);
}
printf("\n");
rewind(orderFile);
/* ******************************************************************* */
/* This will ask which line he wants to change */
do{
printf("Choose the line you want to change\n");
printf("[Line] ");
scanf("%d",&line);
printf("\n");
if(line > i)
{
printf("That line does not exist\n\n");
}
}while(line > i || line < 1);
/* ******************************************* */
/* This will ask for the file name, seconds and time in HH:MM */
printf("Insert the name of the file\n");
printf("[Name] ");
getchar();
scanf("%s",&orderNameFile);
printf("Insert the presentation time in seconds\n");
printf("[Time in seconds] ");
scanf("%d",&orderSecondsFile);
printf("Insert the hour it starts\n");
printf("[Time in HH:MM (Hour:Minutes)] ");
getchar();
scanf("%s%",&orderTimeFile);
/* ******************************************* */
/* This is what is supposed to edit the line I want but does not work */
while(fscanf(orderFile," %49[^;];%d; %49[^\n]",fileName,&seconds,timeValue) == 3)
{
count++;
if(count == line)
{
position = ftell(orderFile);
fseek(orderFile, position, SEEK_SET);
fprintf(orderFile,"%s;%d;%s",orderNameFile,orderSecondsFile,orderTimeFile);
break;
}
}
*/ ****************************************************************** */
fclose(orderFile);
我想要使用第一个示例的输出:
file.txt;10;21:21
file2.txt;3;20:20
file.txt;5;20:00
file4.txt;3;10:00
输出它使用第一个示例@EDITED:
file.txt;10;21:21
file2.txt;3;20:00
file2.txt;30;22:20file.txt;5;20:00
file4.txt;3;10:00
你有什么想法吗?
【问题讨论】:
-
这似乎是与您的变量
linha相关的问题。我看不到它的任何定义,所以我很难判断问题出在哪里。但我想第一个问题是fscanf在最后一个循环中读取该行,将光标移动到文件中,然后您尝试重写该行,重写它之后的数据。您需要将光标返回到行首。 -
对不起,我把所有的东西都翻译成了英文,linha = line。如何将光标放回行首?我只知道如何输入第一行..会检查你的答案。
-
@Ran 您可以在每次 while 迭代之前使用
ftell将位置存储在文件中(例如,在第一次运行声明之前,然后在进行计数时)。当您进入if (count == line)时,您将使用 fseek(orderFile, positionFromFtell, SEEK_SET)。此外,最好打破 if 主体中的 while 循环,向读者发出明确的信号,即它只运行一次。 -
可以尝试复制另一个文件,但不想有很多 txt 文件。而且我们还不知道数据库,我只有 2 天的时间来完成这个。在“工作”项目中,它也要求保存在文件中。 Alegnem,关于如何将“光标”移回来有什么建议吗?