0

我一直在尝试用 C/C++ 创建一个程序,该程序会创建文件,直到进程停止。文件名从 0 开始并遵循等差数列。

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

long cifre(long x) //returns the number of digits a number has
{
    int nr = 0;
    while (x != 0)
    {
        x = x/10;
        nr++;
    }
    return nr;
}

int main()
{
    long i=0;
    FILE* g;
    char* v;
    char buffer[1025];
    int j=0;

    for (j=0;j<1024;j++)
        buffer[j] = 'x';

    while (1)
    {   
        v = (char*)malloc(cifre(i)+10);
        snprintf(v,sizeof(v),"%ld",i);
        g = fopen(v,"w");
        fprintf(g,"%s",buffer);
        free(v);
        fclose(g);
        i++;
    }    
    return 0;
}

问题是程序只创建了 1000 个文件。

4

2 回答 2

3

sizeof(v)sprintf 的调用是 char 指针的大小,在您的情况下可能是 4,这意味着格式化的字符串最多包含 3 个字符,或从 0 到 999 的数字。要解决此问题,请使用您使用的相同长度分配内存:

    size_t len = cifre(i)+10;
    v = (char*)malloc(len);
    snprintf(v,len,"%ld",i);
于 2013-02-09T10:24:28.810 回答
1

snprintf(v,sizeof(v) doesn't make much sense because sizeof(v) returns the size of the pointer (v is char*), not the size of the dynamically allocated array. And so snprintf() is limited to only printing sizeof(v)-1 characters, or 3 digits and the NUL string terminator. 3 digits give you values from 000 to 999, exactly 1000.

于 2013-02-09T10:25:04.250 回答