gpt4 book ai didi

c - 将文本从文件打印到屏幕

转载 作者:行者123 更新时间:2023-11-30 19:51:25 24 4
gpt4 key购买 nike

假设我在文件中放入一些文本,关闭文件后将其打印到屏幕上的最快方法是什么?

例如,在下面的函数中,我使用 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);
}

最佳答案

您可以使用 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);

关于c - 将文本从文件打印到屏幕,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44333522/

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