strncpy 函数生成错误的文件名



我是C语言新手,正在编写代码来帮助我的数据分析。其中一部分打开预定文件。

这段代码给我带来了问题,我不明白为什么。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLOGGERS 26
// Declare the input files
char inputfile[];
char inputfile_hum[MAXLOGGERS][8];
// Declare the output files
char newfile[];
char newfile_hum[MAXLOGGERS][8];
int main()
{
int n = 2;
while (n > MAXLOGGERS)
{
printf("n error, n must be < %d: ", MAXLOGGERS);
scanf("%d", &n);
}
// Initialize the input and output file names
strncpy(inputfile_hum[1], "Ahum.csv", 8);
strncpy(inputfile_hum[2], "Bhum.csv", 8);
strncpy(newfile_hum[1], "Ahum.txt", 8);
strncpy(newfile_hum[2], "Bhum.txt", 8);

for (int i = 1; i < n + 1; i++)
{
strncpy(inputfile, inputfile_hum[i], 8);
FILE* file1 = fopen(inputfile, "r");
// Safety check
while (file1 == NULL)
{
printf("nError: %s == NULLn", inputfile);
printf("nPress enter to exit:");
getchar();
return 0;
}
strncpy(newfile, newfile_hum[i], 8);
FILE* file2 = fopen(newfile, "w");
// Safety check
if (file2 == NULL)
{
printf("Error: file2 == NULLn");
getchar();
return 0;
}
for (int c = fgetc(file1); c != EOF; c = fgetc(file1))
{
fprintf(file2, "%c", c);
}
fclose(file1);
fclose(file2);
}
//  system("Ahum.txt");
//  system("Bhum.txt");
}

此代码生成两个文件,但不是名称:

Ahum.txt
Bhum.txt

这些文件命名为:

Ahum.txtv
Bhum.txtv

我在 for 循环中使用strncpy的原因是因为 n 实际上稍后将由用户输入。

我在这里看到至少三个问题。

第一个问题是你的字符数组对于你的字符串来说太小了。 "哼.txt"等需要九个字符。8 个用于实际文本,另外 1 个用于 null 终止字符。

第二个问题是您已将字符数组"newfile"和"inputfile"声明为空数组。这些还需要是一个能够包含字符串的数字(至少 9 个)。 您很幸运没有因覆盖程序空间的内存而崩溃。

第三个也是最后一个问题是你对strcpy()的使用。 strncpy(dest, src, n) 会将 n 个字符从 src 复制到 dest,但如果 n 等于或小于 src 字符串的大小,它不会复制最终的空终止符字符。

来自 strncpy() manpage: https://linux.die.net/man/3/strncpy

strncpy() 函数 ...最多复制 n 个字节的 SRC。 警告:如果 src 的前 n 个字节中没有空字节, 放置在 Dest 中的字符串不会以 null 结尾。

通常,您要做的是让"n"是目标缓冲区的大小减去 1 以允许空字符。

例如: strncpy(dest, src, sizeof(dest) - 1);假设 dest 是字符数组

你的代码有几个问题。

  1. newfile_hum,inputfile_hum 字符串上的尾随"\0"需要大一个字符。

    字符inputfile_hum[最大记录器][9]; ... 字符newfile_hum[最大记录器][9];

  2. strncpy 期望第一个参数是一个足够大的char *区域来保存预期的结果,因此需要声明 inputfile[] 和 outputfile[]:

    字符输入文件[9]; 字符输出文件[9];

最新更新