我是新来的C编程。现在我正在编写一个程序C它读取 .txt 文件并将数据存储到另一个 txt 文件中。例如:
open 20150101.txt
然后获取里面的数据
2015010103I
2015010102O
然后将其存储在2015JAN.txt
目前我在对 .txt 文件的内容进行排序时遇到问题。你可以帮帮我吗?
int intCtr;
int intCtr2;
int intCtr3;
char strTempData[MAX_SIZE];
FILE * ptrFileLog;
ptrFileLog = fopen(strFileName, "r");
while(fgets(strTRLog, MAX_SIZE, ptrFileLog) != NULL) {
FILE * ptrSummary;
ptrSummary = fopen(strFileSummary, "a");
for(intCtr = 0; intCtr < MAX_SIZE; intCtr++) {
strcpy(strTempCopy[intCtr], strTRLog);
}
for(int intCtr = 0; intCtr < MAX_SIZE; intCtr++) {
for(int intCtr2 = 6; intCtr2 < 7; intCtr2++) {
if(strcmp(strTempCopy[intCtr -1], strTempCopy[intCtr]) > 0) {
strcpy(strTempData, strTempCopy[intCtr]);
strcpy( strTempCopy[intCtr], strTempCopy[intCtr - 1]);
strcpy(strTempCopy[intCtr -1], strTempData);
}
}
}
for(int intCtr = 0; intCtr < 1; intCtr++) {
fputs(strTempCopy[intCtr], ptrSummary);
}
}
fclose(ptrFileLog);
fclose(ptrSummary);
为了解决这个问题,我建议逐行读取并将其存储在字符串列表中。并使用任何排序算法对列表进行排序(此处的示例:冒泡排序)。并将结果打印到新文件中。
不要在 while 循环内打开文件不是一个好主意。在某些情况下,您可能最终会丢失打开文件的处理程序。
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define MAX_LEN 100 // Length of each line in input file.
int main(void)
{
char *strFileName = "C:\\Users\\sridhar\\untitled4\\data.txt";
char *strFileSummary = "C:\\Users\\sridhar\\untitled4\\out.txt";
char strTempData[MAX_LEN];
char **strData = NULL; // String List
int i, j;
int noOfLines = 0;
FILE * ptrFileLog = NULL;
FILE * ptrSummary = NULL;
if ( (ptrFileLog = fopen(strFileName, "r")) == NULL ) {
fprintf(stderr,"Error: Could not open %s\n",strFileName);
return 1;
}
if ( (ptrSummary = fopen(strFileSummary, "a")) == NULL ) {
fprintf(stderr,"Error: Could not open %s\n",strFileSummary);
return 1;
}
// Read and store in a string list.
while(fgets(strTempData, MAX_LEN, ptrFileLog) != NULL) {
// Remove the trailing newline character
if(strchr(strTempData,'\n'))
strTempData[strlen(strTempData)-1] = '\0';
strData = (char**)realloc(strData, sizeof(char**)*(noOfLines+1));
strData[noOfLines] = (char*)calloc(MAX_LEN,sizeof(char));
strcpy(strData[noOfLines], strTempData);
noOfLines++;
}
// Sort the array.
for(i= 0; i < (noOfLines - 1); ++i) {
for(j = 0; j < ( noOfLines - i - 1); ++j) {
if(strcmp(strData[j], strData[j+1]) > 0) {
strcpy(strTempData, strData[j]);
strcpy(strData[j], strData[j+1]);
strcpy(strData[j+1], strTempData);
}
}
}
// Write it to outfile. file.
for(i = 0; i < noOfLines; i++)
fprintf(ptrSummary,"%s\n",strData[i]);
// free each string
for(i = 0; i < noOfLines; i++)
free(strData[i]);
// free string list.
free(strData);
fclose(ptrFileLog);
fclose(ptrSummary);
return 0;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)