我不太确定C中的函数printf何时会返回一个负数。 我知道printf在打印字符串失败时会返回一个负数,很可能是-1。 但我想知道为什么以及何时它将无法打印字符串。 例如我的代码在这里:什么时候会printf返回一个负数?
#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;
}
中的printf打印在打印功能整数var.age和var.yearofbirth总是返回一个负数。该行
printf("%s\n", var.name);
在函数打印成功,但就这些了。但在我的Data.txt中,每个人的年龄和出生年份都非常明确,如下所示。
Name Age YearofBirth
那么,为什么printf会返回一个负数呢? 谢谢你,
[C]中printf()函数的返回值的可能重复(http://stackoverflow.com/questions/7055882/return-value-of-printf-function-in-c) – John3136
您的两个后续'printf如果第一个成功并返回一些积极的东西,它们甚至不会被执行。 – tkausl
[手册页](https://linux.die.net/man/3/printf)指出'如果遇到输出错误,则返回负值。 '。如果发生这种情况,请查看[errno](https://linux.die.net/man/3/errno)以查明哪里出了问题。并且提出一个温和的请求:下次请在发布之前清理你的代码,这些注释掉的块与你遇到的问题无关,而且很难阅读代码,而且看起来不整洁。 – fvu