在尝试增加int变量的值时,我遇到了使用increment++的问题。我将名为records的变量的地址传递给函数open(),然后以二进制模式打开文件,然后解析文件以查找文件中存在的结构记录元素的数量。问题是,当使用增量++作为
*records++;
结果不是预期的,例如,我在.dat文件中有4条记录,它会打印:
HELLO! 1
HELLO! 0
HELLO! -251258176
HELLO! 22074
总的来说,它打印:
Records in file: 0.
现在奇怪的是,我没有使用增量++,而是使用
*records += 1;
,结果不出所料!
HELLO! 1
HELLO! 2
HELLO! 3
HELLO! 4
总的来说:
Records in file: 4.
我不明白问题出在哪里。部分代码包含在下面:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define true 1
#define false 0
#define size 100
typedef struct record {
char firstName[size], lastName[size];
int age;
double grade;
} record;
int open(const char *filename, FILE **fp, int *records);
int main() {
FILE *fp;
char filename[] = "records.dat";
int records = 0, opened = false, ch = 1;
while(ch > 0 && ch < 5) {
printf("Select your choice from the list below: \n");
printf("1. Open file and get amount of records in it\n");
printf("Enter your choice: ");
scanf("%d", &ch);
while(getchar() != '\n');
switch(ch) {
case 1:
if(opened) {
printf("\nFile already open, try closing it first please.\n");
break;
}
opened = open(filename, &fp, &records);
if(opened) {
printf("\nRecords in file: %d.\n", records);
} else { // Failed to open AND create file
return 1;
}
break;
default:
printf("\nGoodbye!\n");
if(opened) {
fclose(fp);
}
return 0;
break;
}
}
}
int open(const char *filename, FILE **fp, int *records) {
char temp[size];
record r;
*records = 0;
printf("Attempting to open file...\n");
*fp = fopen(filename, "rb+");
if(*fp == NULL) {
printf("File doesn't exit, attempting to create file...\n");
*fp = fopen(filename, "wb+");
if(*fp == NULL) {
fprintf(stderr, "Couldn't open neither create %s, exiting...\n", filename);
return false;
}
printf("File created.\n");
return true;
}
printf("File found!\n");
while(fread(&r, sizeof(r), 1, *fp) == 1) {
*records++;
//*records += 1;
printf("HELLO! %d\n", *records);
}
return true;
}