gpt4 book ai didi

在 C 中复制数组并清除 char 数组中的垃圾

转载 作者:太空宇宙 更新时间:2023-11-04 03:42:40 25 4
gpt4 key购买 nike

我正在尝试将一个大字符串与一个像 "https://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png"只有 url 和 NULL 终止符 https://cdn.sstatic.net/stackexchange/img/logos/so/so-logo.png\0 的较小数组,但我得到了垃圾数组。

问题应该出在这里:

pos2 = 0;
while (found == 0)
{
c = fgetc (fp); // get char from file
link[pos2] = c;
if (link[pos2-1] == 'g' && link[pos2] == '\"') // png and jpg files
{
found = 1;
}
++pos2;
}
--pos2;
found = 0;
char link2[pos2];
for (j = 1; j < pos2; ++j)
{
link2[j-1] = link[j];
}
link2[j] = '\0';
//sprintf(cmd, "wget -O /home/arturo/Dropbox/Digital_Renders/%d \'%s\'", ++num, link2);
//system(cmd);
printf("%s\n", link2);// checking
sleep(1);

代码如下:

#include <stdio.h>
#include <stdlib.h> // for using system calls
#include <unistd.h> // for sleep

int main ()
{
char body[] = "forum-post-body-content", notes[] = "p-comment-notes", img[] = "img src=", link[200], cmd[200]={0}, file[10];
int c, pos = 0, pos2 = 0, fin = 0, i, j, num = 0, found = 0;
FILE *fp;

for (i = 1; i < 500; ++i)
{
sprintf(cmd,"wget -O page%d.txt 'http://www.mtgsalvation.com/forums/creativity/artwork/340782-official-digital-rendering-thread?page=%d'",i,i);
system(cmd);
sprintf(file, "page%d.txt", i);
fp = fopen (file, "r");
while ((c = fgetc(fp)) != EOF)
{
if (body[pos] == c)
{
if (pos == 22)
{
pos = 0;
while (fin == 0)
{
c = fgetc (fp);
if (feof (fp))
break;
if (notes[pos] == c)
{
if (pos == 14)
{
fin = 1;
pos = -1;
}
++pos;
}
else
{
if(pos > 0)
pos = 0;
}
if (img[pos2] == c)
{
if (pos2 == 7)
{
pos2 = 0;
while (found == 0)
{
c = fgetc (fp); // get char from file
link[pos2] = c;
if (pos2 > 0)
{
if(link[pos2-1] == 'g' && link[pos2] == '\"')
{
found = 1;
}
}
++pos2;
}
--pos2;
found = 0;
char link2[pos2];
for (j = 1; j < pos2; ++j)
{
link2[j - 1] = link[j];
}
link2[j - 1] = '\0';
//sprintf(cmd, "wget -O /home/arturo/Dropbox/Digital_Renders/%d \'%s\'", ++num, link2);
//system(cmd);
printf("%s\n", link2);// checking
sleep(1);
pos2 = -1;
}
++pos2;
}
else
{
if(pos2 > 0)
pos2 = 0;
}
}
fin = 0;
}
++pos;
}
else
pos = 0;
}
// closing file
fclose (fp);
if (remove (file))
{
fprintf(stderr, "Can't remove file\n");
}
}
}

最佳答案

鉴于声明:

char cmd[50];

这条线不好:

sprintf(cmd,"wget -O page%d.txt 'http://www.mtgsalvation.com/forums/creativity/artwork/340782-official-digital-rendering-thread?page=%d'",i,i);

您正试图将 120 多个字符打包到一个 50 字节的缓冲区中;这不会可靠地工作。

关于在 C 中复制数组并清除 char 数组中的垃圾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27320046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com