这段代码有何问题int FindLinesInCSV(FILE* Fp) { fseek(Fp, 0, 0);//将文件指针重新指向文件开头 char ch[1024] = {0};//缓冲区域 int nLine = 0; if (SuccessfulOpen(Fp)) { cout << "wrong path !" << endl; return 0; } else { while (fgets(ch,1024,Fp) != NULL) {//每次在缓冲区域中输入一行数据 nLine++; } } return (nLine); }
时间: 2024-01-04 09:03:02 浏览: 77
这段代码存在以下问题:
1. 变量`nLine`未被初始化:在函数开始时,应该将变量`nLine`初始化为0。
2. `SuccessfulOpen`函数未定义:应该先定义或包含该函数。
3. `fseek`函数调用不必要:在函数调用之前,文件指针默认已经指向文件开头。
4. `fgets`函数调用不安全:当读取到的数据长度大于缓冲区大小时,可能会导致缓冲区溢出。应该使用`fgets(ch, sizeof(ch), Fp)`,其中`sizeof(ch)`返回缓冲区大小。
改进后的代码如下:
```c++
int FindLinesInCSV(FILE* Fp) {
char ch[1024] = {0}; // 缓冲区域
int nLine = 0;
while (fgets(ch, sizeof(ch), Fp) != NULL) { // 每次在缓冲区域中输入一行数据
nLine++;
}
return nLine;
}
```
相关问题
int SearchCitiesSerialNumber(char* Temp, CITIES* pCity, FILE* Fp) { fseek(Fp, 0, 0);//将文件指针重新指向文件开头 int nLine = FindLinesInCSV(Fp);//得到文件中共有几行数据 for (int i = 0; i < nLine; i++) { if (!strcmp(pCity[i].cCity, Temp))return i; } return -1; }
这段代码的功能是在城市数组中搜索指定城市名并返回其在数组中的序号。具体来说,该函数首先使用 FindLinesInCSV() 函数获取城市数组中的元素个数,然后使用 for 循环遍历整个数组,逐一比较每个元素的城市名是否与指定的城市名相同。如果找到了匹配的城市名,则返回该城市在数组中的序号。如果遍历完整个数组后仍未找到匹配的城市名,则返回 -1。需要注意的是,该函数还包含了一些错误处理代码,例如在文件打开失败时返回 -1。
fseek(fp,0,SEEK_CUR);
`fseek()` 函数用于设置文件指针的位置,它接受三个参数:
1. `FILE *_File`: 指向要操作的文件的指针。
2. `long _Offset`: 要移动到的新位置,以字节为单位。
3. `int _Origin`: 移动的起始点,有三种选择:
- `SEEK_SET` (通常为0): 从文件开始处(即文件头)定位。
- `SEEK_CUR` (默认): 从当前位置开始定位。
- `SEEK_END`: 从文件结束处定位。
当你调用 `fseek(fp, 0, SEEK_CUR)` 时,它会将文件指针fp向前移动当前位置的偏移量为0。如果fp已经位于文件的开头,这个调用实际上不会改变指针位置,但如果fp在文件中间,它会移到当前位置。这是一个相对定位的例子,表示从当前位置开始移动。请注意,这个函数返回一个非零值表示成功,0表示失败。
示例:
```c
#include <stdio.h>
int main() {
FILE* file = fopen("test.txt", "r+b"); // 假设已打开一个文件
if (file == NULL) {
printf("Error opening the file.\n");
return 1;
}
// 初始读取文件指针位置
long initial_position = ftell(file);
// 使用fseek将文件指针移到当前位置之前
if (fseek(file, 0, SEEK_CUR)) {
perror("Error seeking in the file.");
fclose(file);
return 1;
}
// 新位置可能与初始位置相同,取决于文件指针原来的位置
long new_position = ftell(file);
printf("New position after fseek: %ld\n", new_position);
fclose(file);
return 0;
}
```
阅读全文
相关推荐

















