【发布时间】:2016-03-08 01:46:31
【问题描述】:
我遇到了一个我找不到的问题解决方案。
我正在将两个文本文件合并到第三个文件中,并且我想跟踪我正在移动的数据。到目前为止,代码只做一件事,完全忽略了另一件事。
代码如下:
// enable standard c i/o functions
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
int main()
{
// Open two files to be merged
FILE *fp1 = fopen("test1.txt", "r");
FILE *fp2 = fopen("test2.txt", "r");
// Open file to store the result
FILE *fp3 = fopen("results.txt", "w+");
char c;
int count2ch = 0; // count meter for characters
int count1ch = 0; // count meter for characters
int totalch = 0; // holds number of total ammount of characters
int count1wd = 0; // count meter for words
int count2wd = 0; // count meter for words
int totalWD = 0;// holds total ammount of words
// Check files
if (fp1 == NULL || fp2 == NULL || fp3 == NULL)
{
puts("Could not open file");
exit(0);
}
// COUNTING CHARACTERS
// count characters file one
while (1)
{
c = fgetc(fp1);
if (c == EOF)
break;
count1ch++;
}
// count characters file two
while (1)
{
c = fgetc(fp2);
if (c == EOF)
break;
count2ch++;
}
//MERGING FILES
// Copy contents of first file to file3.txt
while ((c = fgetc(fp1)) != EOF)
fputc(c, fp3);
// Copy contents of second file to file3.txt
while ((c = fgetc(fp2)) != EOF)
fputc(c, fp3);
// COUNTING WORDS
//count words file one
while ((c = fgetc(fp1)) != EOF)
{
if (c == ' ')
count1wd++;
}
//count words file two
while ((c = fgetc(fp2)) != EOF)
{
if (c == ' ')
count2wd++;
}
// count total ammount of words
totalWD = count1wd + count2wd;
// count total ammount of characters
totalch = count1ch + count2ch;
printf("Merged file1.txt and file2.txt into file3.txt \n");
printf("Total number of characters moved: %d\n", totalch);
printf("The ammount of chars in your first file is : %d\n", count1ch);
printf("The ammount of chars in your second file is : %d\n", count2ch);
printf("Total number of words moved: %d\n", totalWD);
printf("The ammount of words in your fist file is : %d\n", count1wd);
printf("The ammount of words in your second file is : %d\n", count2wd);
fclose(fp1);
fclose(fp2);
fclose(fp3);
return 0;
}
现在,它只是将两个文件合并到第三个文件中,仅此而已。如果我将计数单词或字符部分移到合并部分上方,代码将执行任何先到的操作。
【问题讨论】:
-
你需要
fseek回到文件的开头。在每组fgetc调用完成后,因为它们将文件指针留在文件末尾。 -
正如 kaylum 所说,跟踪您的文件指针。只要您首先浏览整个文件,
rewind()。我们不需要取消那些只使用的函数:(当然fseek(fp, 0, SEEK_SET)确实有效,但它不如rewind(fp)漂亮。
标签: c