strncpy函数产生错误的文件名

strncpy函数产生错误的文件名,strncpy,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]; // Decl

我是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 == NULL\n", 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 == NULL\n");
            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.txtv
Bhum.txtv

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

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

第一个问题是字符数组对于字符串来说太小。 ahum.txt等将需要九个字符。八个用于实际文本,另一个用于空终止字符

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

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

从strncpy手册页:

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

通常,您要做的是将n设置为目标缓冲区的大小减去1,以允许使用空字符

例如:
strncpydest,src,sizeofdest-1;//假设dest是char数组

,那么您的代码有几个问题

inputfile\u hum,newfile\u hum,对于字符串上的尾随“\0”,需要大一个字符

字符输入文件_hum[MAXLOGGERS][9]; ... char newfile_hum[MAXLOGGERS][9]

strncpy希望第一个参数是一个足够大的char*区域,以容纳预期的结果,因此需要声明inputfile[]和outputfile[]:

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


Thanx,现在它工作了!但是我声明大小为8的字符数组的原因是因为我还计算了0。inputfile_-hum[MAXLOGGERS][8]实际上不是有9个字符的空间吗?[0]:A[1]:h[2]:u[3]:m[4]:,[5]:t[6]:x[7]:t[8]:\n它工作正常。数组大小是实际大小,而不是最高索引的值。8的数组的索引范围为0到7。如果此帮助需要15个声誉,请向上投票!您需要9个空格的内存来存储8个字符,因为需要额外的\0来终止c字符串
Ahum.txtv
Bhum.txtv