我正在写一个函数(*rwObjects()
),它将读取一个格式化的文件并保存它的字符串,一次一个对象。不幸的是,这对我的学习有限制 - stdio.h,stdlib.h和string.h几乎是我所能使用的。
这就是问题所在:每当我运行代码时,当它到达fclose(input)
时,VS17表示我的项目触发了一个断点,然后打开一个标签,上面写着“wntdll.pdb not loaded”或其他东西。
问题是:如何不触发断点并正确关闭文件?或者,如果问题不在文件中,它在哪里?
代码(C):
#define _CRT_SECURE_NO_WARNINGS
#define cnCOUNTRY_LENGTH 3
#define cnOBJECT_NAME_LENGTH 30
#define cnOBJECT_MAX 1000
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//--Поле объекта objectType--
//Country (0) - строка названия страны
//ObjectName (1) - строка названия объекта
//Square (2) - площадь объекта
//Error (3) - ошибка в содержании строки
typedef enum IOOptions {Country, ObjectName, Square, Error} IOType;
//--Тип обрабатываемых объектов--
//char Country - строка названия страны
//char ObjectName - строка названия объекта
//int Square - площадь объекта
typedef struct object {
char Country[cnCOUNTRY_LENGTH];
char ObjectName[cnOBJECT_NAME_LENGTH];
int Square;
} objectType;
//--Копирование текущего элемента строки objects.txt--
//strMod - Строка, в которую идёт копирование
//strPos - Позиция в считываемой строке
//strBlueprint - Строка, из которой идёт копирование
//writeType - Поле объекта objectType. При "Country" - переводит вводимые символы в верхний регистр ('a' -> 'A' и т.д.)
void copyInputStr(char *strMod, int *strPos, char *strBlueprint, IOType writeType) {
for (*strPos; *strBlueprint != ' ' && *strBlueprint != '\n' && *strBlueprint != NULL; *strPos = *strPos + 1) {
*strMod = *strBlueprint;
if (writeType == Country) toupper(*strMod);
strBlueprint++; strMod++;
}
}
//--Запись текущего элемента строки objects.txt в текущий объект--
//strInput - Строка, из которой идёт запись
//objectOutput - Объект, в который идёт запись
//writeType - Поле объекта, в которое идёт запись
void writeObject(char *strInput, objectType *objectOutput, IOType writeType) {
if (writeType == Country)
strcpy(objectOutput->Country, strInput);
else if (writeType == ObjectName)
strcpy(objectOutput->ObjectName, strInput);
else if (writeType == Square)
objectOutput->Square = atoi(strInput);
else printf("Error 1. Invalid parameters");
}
//--Чтение objects.txt и запись в массив objectType--
//Возвращает указатель на первый элемент массива объектов
objectType *rwObjects() {
FILE *input = fopen("objects.txt", "r");
char objectQttStr[4], objectStr[38];
fgets(objectQttStr, 4, input);
objectType *objectList = (objectType *)malloc(atoi(objectQttStr)), *currentObject = objectList;
currentObject = (objectType *)malloc(atoi(objectQttStr));
for (int i = 0; i < atoi(objectQttStr); i++) {
fgets(objectStr, 38, input);
IOType inputType = Country;
for (int j = 0; objectStr[j] != NULL && objectStr[j] != '\n'; j++) {
char strBuf[cnOBJECT_NAME_LENGTH];
memset(&strBuf, 0, sizeof(strBuf));
copyInputStr(&strBuf, &j, &objectStr[j], inputType);
writeObject(&strBuf, currentObject, inputType);
inputType++;
}
currentObject++;
}
fclose(input); //this is where it happens
return objectList;
}
void main() {
objectType *objectList = rwObjects();
printf("");
}
这是一个令人困惑的程序,但我找不到其他方法来符合血腥的规则,所以让我们把编码风格放在一边,好吗?
此外,我知道如果它成功运行,什么都不会发生 - 这是设计的。它尚未完成。
编辑:不要担心输入数据的有效性。所有输入数据格式都在任务中明确说明,而不需要检查。不过,对于好奇的人来说,这里是:
objects.txt:
3
USA WelfareArrangement 120
Rus PoiskZemli 30
usa asdfEstate 1
编辑2:我停止使用malloc的那一刻,一切都很好。问题是 - 为什么这是一个问题,如何创建一个我需要的确切大小的数组,而不是创建最大大小evey时间,如果没有malloc?
第一个问题:
objectType *objectList = (objectType *)malloc(atoi(objectQttStr)), *currentObject = objectList;
currentObject = (objectType *)malloc(atoi(objectQttStr));
malloc
函数分配给定的字节数。因此,如果您有5个对象,则只分配5个字节。这对你的结构来说还不够。这会导致您编写超出调用undefined behavior的已分配内存的末尾。
如果要为特定数量的对象分配空间,则需要乘以对象大小:
objectType *objectList = malloc(sizeof(*objectList)*atoi(objectQttStr));
还有,don't cast the return value of malloc
。
您还将currentObject
指定为与objectList
相同的值,但随后使用单独的内存分配覆盖它。所以摆脱第二个malloc
。
第二个问题:
memset(&strBuf, 0, sizeof(strBuf));
copyInputStr(&strBuf, &j, &objectStr[j], inputType);
writeObject(&strBuf, currentObject, inputType);
你的copyInputStr
和writeObject
函数期望一个char *
,但是你传递了strBuf
类型的char (*)[30]
数组的地址。摆脱这里的地址运营商:
memset(strBuf, 0, sizeof(strBuf));
copyInputStr(strBuf, &j, &objectStr[j], inputType);
writeObject(strBuf, currentObject, inputType);
第三个问题:
void copyInputStr(char *strMod, int *strPos, char *strBlueprint, IOType writeType) {
for (*strPos; *strBlueprint != ' ' && *strBlueprint != '\n' && *strBlueprint != NULL; *strPos = *strPos + 1) {
*strMod = *strBlueprint;
if (writeType == Country) toupper(*strMod);
strBlueprint++; strMod++;
}
}
当您复制strMod
中的字符时,您最后不会添加空字节。 C中的字符串是以空字符结尾的字符数组,因此您最终得到的不是字符串而只是字符数组。当你稍后在这个数组上调用strcpy
时,该函数找不到空字节,因此它会一直读取,直到它为止。这会导致函数读取未初始化的字节和/或读取数组的末尾,这再次调用未定义的行为。
在循环之后添加空终止字节。此外,toupper
函数的结果未分配给任何东西,因此它什么都不做。你需要将它分配回*strMod
:
void copyInputStr(char *strMod, int *strPos, char *strBlueprint, IOType writeType) {
for (*strPos; *strBlueprint != ' ' && *strBlueprint != '\n' && *strBlueprint != NULL; *strPos = *strPos + 1) {
*strMod = *strBlueprint;
if (writeType == Country) *strMod = toupper(*strMod);
strBlueprint++; strMod++;
}
*strMod = 0;
}