我在C中的I / O文件处理过程中遇到了几个问题。我有一个像这样的文本文件:
AAA 1 80
BBB 1 60
CCC 2 20
DDD 1 70
EEE 2 15
FFF 2 30
GGG 2 75
HHH 1 25
JJJ 2 35
我的目标是,如果用户输入1我需要打印:
AAA 1 80
BBB 1 60
DDD 1 70
HHH 1 25
并求和它们的值(80 + 60 + 70 + 25),并在用户输入2时应用相同的内容。
我编写这样的代码:
FILE *fPtr;
char str[MAXCHAR];
char* fileName = "/home/levent/Masaüstü/data.txt";
int productType;
fPtr = fopen(fileName, "r");
if(fPtr == NULL){
printf("Error! Colud not find file %s", fileName);
return 1;
}
printf("Enter product type code (1 or 2): ");
scanf("%d", &productType);
while (fgets(str, MAXCHAR, fPtr) != NULL){
printf("%s", str);
}
当您假设此代码可打印整个文本文件时。如何管理目标?
You can use
fscanf
and read each component of the line since you know what they are, then in the same cycle you can sum the valid values:这是一个可能的实现,并带有一些注释:
another option would be to use
sscanf
to extract the components from the string read byfgets
.