I am not so sure when the function printf in C will return a negative number. I know that printf will return a negative number, most likely -1, when it has failed to print a string. But I want to know why and when it will fail to print a string. For instance my code here:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#pragma pack(1)
typedef struct{
char name[14];
int age;
int yearofbirth;
}person;
int print(person var)
{
if(printf("%s\n", var.name)<0)
{
if(printf("%d\n", var.age)<0)
{
if(printf("%d\n\n", var.yearofbirth)<0)
{
return 1;
}
}
}
return 0;
}
int main(void)
{
int i=0;
person thing;
FILE* file=fopen("Data.txt", "r");
if(file)
{
long amountofstruct = 0;
char* z=(char*)malloc(sizeof(char)*200);
while(fgets(z,100,file)!=NULL)
{
amountofstruct++;
}
fseek(file,0,SEEK_END);
free(z);
int k=0;
/* while(k<amountofstruct)
{
fseek(file,sizeof(person)*k,SEEK_SET);
fread(&function[k], sizeof(person),1,file);
k++;
}
int szt;
printf("%p",function);
for(szt=0;szt<amountofstruct;szt++)
{
printf("Person %d:\tName:%s\t Age:%i\t Year Of Birth:%i\n",szt+1,function[szt].name,function[szt].age,function[szt].yearofbirth);
}*/
printf("thesizeofstruct:%ld\n",sizeof(person));
printf("%ld",amountofstruct);
//thing.name = {' ',' ',' ',' ',' ',' ',' ',' ',' ','\0'};
char *l = (char*)malloc(11);
while(k<amountofstruct)
{
fseek(file,sizeof(person)*k,SEEK_SET);
if(fread(&thing, sizeof(thing), 1, file)!=0)
{
thing.name[13]='\0';
// printf("sizeof(thing string)%lu\n sizeof(thing)%lu\n", sizeof(thing.name),strlen(thing.name));
if(print(thing)==0)
{
printf("\nThe thing failed, sorry");
return 0;
}
//char *p = strchr(thing.name, ' ');
// *p='\0';
// strcpy(l,thing.name);
//printf("Person %d: \t Name: %s\t Age: %d\t Year Of Birth: %d\n", k+1, l, thing.age, thing.yearofbirth);
// thing.name[0]='\0';
// thing.age=0;
// thing.yearofbirth=0;
k++;
}
}
free(l);
}
else
{
perror("The file could not be opened");
}
getchar();
return 0;
}
the printf printing the integers var.age and var.yearofbirth in function print always returns a negative number. The line
printf("%s\n", var.name);
in function print succeeds, but that's all. But in my Data.txt, the age and the year of birth of each person is very clearly provided as follows.
Name Age YearofBirth
So why is it that printf would return a negative number? Thank You,