I'm reading a string from a file and then, trying to add zeros to the string till it reach 100, and then I'm printing the string, but I don't know what's wrong, I've tried more than one approach , but they all seems not to work.
int main(int argc, char *argv[])
{
if (argc != 2 ){
fprintf(stderr, "usage: server filename \n");
exit(1);
}
FILE *file = fopen(argv[1], "r");
if (file==0)
{
printf("file couldn't be opened\n");
exit(1);
}
int i;
char str1[100];
//char str2[100];
//memset(str2,0,sizeof(str2));
//for(i = 0; i < 100; i++)
// fprintf(stdout, "str2[%u]: %u\n",i,str2[i]);
while (fscanf(file, "%s", str1) != EOF)
{
for(i=13 ; i < 100; i++)
str1[i]=0;
}
for(i = 0; i < 100; i++)
fprintf(stdout, "str1[%u]: %u\n",i,str1[i]);
return 0;
}
but I print it I got
str1[0]: 119
str1[1]: 111
str1[2]: 114
str1[3]: 108
str1[4]: 100
str1[5]: 0
str1[6]: 0
str1[7]: 0
up till 99
I don't understand this although there is a string in the file "hello" and then I've tried this
int main(int argc, char *argv[])
{
if (argc != 2 ){
fprintf(stderr, "usage: server filename \n");
exit(1);
}
FILE *file = fopen(argv[1], "r");
if (file==0)
{
printf("file couldn't be opened\n");
exit(1);
}
int i;
char str1[12];
char str2[100];
memset(str2,0,sizeof(str2));
//for(i = 0; i < 100; i++)
// fprintf(stdout, "str2[%u]: %u\n",i,str2[i]);
while (fscanf(file, "%s", str1) != EOF)
{
strcpy(str2,str1);
}
for(i = 0; i < 100; i++)
fprintf(stdout, "str2[%u]: %u\n",i,str2[i]);
return 0;
}
and I gave me the exact same result as the first one, so I don't understand what is happening here, and why I'm getting these results. I'll be grateful if you can explain what I'm doing wrong here. Thanks in advance.
char str[100]={'0'}
you are creating an array, where the first element is the character zero, and the rest of the elements are null.