|
发表于 2023-9-10 16:34:24
|
显示全部楼层
这些错误信息都是因为使用了不安全的函数,可以按照错误信息中给出的建议,使用对应的安全函数,或者在代码开头加上#pragma warning(disable:4996)来禁用这些警告。具体修改如下:
1. 将fopen改为fopen_s,修改后的代码如下:
- FILE* fp;
- int count = 0;
- int temp;
- if (fopen_s(&fp, filename, "r") != 0)
- {
- fprintf(stderr, "Can not open the file:%s\n", filename);
- return 0;
- }
复制代码
2. 将strcpy改为strcpy_s,修改后的代码如下:
- char thePath[MAX], target[MAX];
- strcpy_s(thePath, MAX, path);
复制代码
3. 将strcat改为strcat_s,修改后的代码如下:
- if ((handle = _findfirst(strcat_s(thePath, MAX, "/*.c"), &fa)) != -1L)
复制代码
4. 将sprintf改为sprintf_s,修改后的代码如下:
- sprintf_s(target, MAX, "%s/%s", path, fa.name);
复制代码
另外,建议在使用_findfirst函数前先判断路径是否存在,可以使用_access函数来判断,修改后的代码如下:
- if (_access(path, 0) == -1)
- {
- fprintf(stderr, "The path %s does not exist!\n", path);
- return 0;
- }
复制代码
修改后的完整代码如下:
- #include<io.h>
- #include<direct.h>
- #include<stdlib.h>
- #include<stdio.h>
- #include<string.h>
- #define MAX 256
- long total;
- int countLines(const char* filename);
- void findAllCodes(const char* path);
- void findALLDirs(const char* path);
- int countLines(const char* filename)
- {
- FILE* fp;
- int count = 0;
- int temp;
- if (fopen_s(&fp, filename, "r") != 0)
- {
- fprintf(stderr, "Can not open the file:%s\n", filename);
- return 0;
- }
- while ((temp = fgetc(fp)) != EOF)
- {
- if (temp == '\n')
- {
- count++;
- }
- }
- fclose(fp);
- return count;
- }
- void findAllCodes(const char* path)
- {
- struct _finddata_t fa;
- long handle;
- char thePath[MAX], target[MAX];
- if (_access(path, 0) == -1)
- {
- fprintf(stderr, "The path %s does not exist!\n", path);
- return;
- }
- strcpy_s(thePath, MAX, path);
- if ((handle = _findfirst(strcat_s(thePath, MAX, "/*.c"), &fa)) != -1L)
- {
- do
- {
- sprintf_s(target, MAX, "%s/%s", path, fa.name);
- total += countLines(target);
- } while (_findnext(handle, &fa) == 0);
- }
- _findclose(handle);
- }
- void findALLDirs(const char* path)
- {
- struct _finddata_t fa;
- long handle;
- char thePath[MAX];
- if (_access(path, 0) == -1)
- {
- fprintf(stderr, "The path %s does not exist!\n", path);
- return;
- }
- strcpy_s(thePath, MAX, path);
- if ((handle = _findfirst(strcat_s(thePath, MAX, "/*"), &fa)) == -1L)
- {
- fprintf(stderr, "The path %s is wrong!\n", path);
- return;
- }
- do
- {
- if (!strcmp(fa.name, ".") || !strcmp(fa.name, ".."))
- continue;
- if (fa.attrib == _A_SUBDIR)
- {
- sprintf_s(thePath, MAX, "%s/%s", path, fa.name);
- findAllCodes(thePath);
- findALLDirs(thePath);
- }
- } while (_findnext(handle, &fa) == 0);
- _findclose(handle);
- }
- int main()
- {
- char path[MAX] = ".";
- printf("计算中...\n");
- findAllCodes(path);
- findALLDirs(path);
- printf("目前你总共写了%ld行代码!\n\n", total);
- system("pause");
- return 0;
- }
复制代码 |
|