【发布时间】:2014-12-05 10:11:54
【问题描述】:
我正在从预读文件中读取数据并将其存储在缓冲区中,我在缓冲区中运行了一个结构来组织数据,然后将其重新保存到另一个文件中。
但是我只阅读了一行代码。
我的代码 - 打开文件:
File *p_file
char fileLocation[40];
char buff[1000];
printf("\nEnter file name: \n");
scanf("%s, fileLocation);
p_file = fopen(fileLocation, "r");
if(!p_file)
{
printf("\nError!\n");
}
循环读取数据并保存文件
while(fgets(buff, 1000, p_file)!=NULL
{
printf("%s", buff);
storedData.source = atoi(strtok(buff, ":");
storedData.destination = atoi(strtok(0, ":");
storedData.type = atoi(strtok(0, ":");
storedData.port = atoi(strtok(0, ":");
storedData.data = strtok(0, ":\n");
printf("\nEnter a File Name to save:");
scanf("%s", fileLocation);
if ((p_file = fopen(fileLocation, "w")) == NULL
{
puts("\n Could not point to the file.");
}else{
printf("\nSaving");
fprintf(p_file, "%04d:%04d:%04d:%04:%s \n",
storedData.source,
storedData.destination,
storedData.type,
storedData.port,
storedData.data );
fclose(p_file);
}
fclose(p_file);
当前输出数据:
0001:0002:0003:0021:CLS
想要的数据输出:
0001:0002:0003:0021:CLS
0001:0010:0003:0021:CLS
0001:0002:0002:0080:<HTML>
我相信我必须声明一个整数值以用于循环文件内容以及使用 malloc 来获取结构的大小,但我不知道我将如何去做。任何帮助都感激不尽。
【问题讨论】:
-
这一行:while(fgets(buff, 1000, p_file)!=NULL is missing a trailing ')'
-
这一行: if ((p_file = fopen(fileLocation, "w")) == NULL is missing a trailing ')' 也为文件指针使用不同的名称,否则 1)将无法进一步引用第一个文件,2) 将无法关闭第一个文件 3) 只需要打开一次输出文件,因此放置在 loo 之外;