假设我在文件中放了一些文字,关闭文件后将它打印到屏幕上的最快方法是什么?
例如,在以下函数中,我使用printf将一些文本放入文件中。 我希望该文字成为屏幕的输出。
void calcMemoryOfVariables(char str[], char* filename)
{
int i = 0, j = 0;
int temp = 1;
int size;
char* tempChar = (char*)malloc((strlen(str))*sizeof(tempChar));
FILE *f=fopen(filename,"w");
if (f==NULL)
exit(1);
while (str[i]!=' ' || str[i]=='*') //checking the type of the variable//
{
tempChar[j] = str[i];
i++;
j++;
}
tempChar[j] = '\0';
size = calcSize(tempChar); //the size of that variavle in bytes//
j = 0;
i++;
while (str[i] != ';')
{
if ((str[i]>='a' && str[i]<='z') || (str[i]>='A' && str[i]<='Z')) // for variables and arrays//
{
while (str[i] != ',' )
{
if (str[i]==' ')
{
while (str[i]==' ')
i++;
}
if (str[i] == '[') //checks if it is an array//
{
printf("%c", str[i]);
i++;
while (str[i] != ']')
{
tempChar[j] = str[i]; //copies the value in the string//
i++;
j++;
}
tempChar[j] = '\0';
temp = strToInt(tempChar); //converting to int in order to valuate the bytes//
}
printf("%c", str[i]);
i++;
if (str[i]==' ')
{
while (str[i]==' ')
i++;
}
}
fprintf(f," requires %d bytes \n", temp*(sizeof(temp)));
}
if (str[i] == '*') //for pointers//
{
while (str[i] != ',' && str[i] != ';')
{
printf("%c", str[i]);
i++;
if (str[i]==' ')
{
while (str[i]==' ')
i++;
}
}
fprintf(f," requires %d bytes \n", 4);
}
if (str[i] != ';')
i++;
}
fclose(f);
}
答案 0 :(得分:-1)
您可以使用sprintf将文本写入数组。 这将允许您将文本写入文件并将其打印在文件上 屏幕:
char output[16];
FILE* fd = fopen("output.txt", "w");
sprintf(output, "%s", "Output Test\n");
printf("%s", output);
fwrite(output, 1, strlen(output), fd);
fclose(fd);