简体   繁体   English

如何在C中将多行写入输出文件?

[英]How to write multiple lines to a output file in C?

I am new to file operations like write/read in C. Is there a solution to write all printf() which is below, to my output text file? 我不熟悉C中的写入/读取等文件操作。是否有解决方案将下面的所有printf()写入我的输出文本文件? After execution I was not able to write all the lines to my text file. 执行后,我无法将所有行写入文本文件。

for(i=0;i < n;i++)
    if(i!=startnode)
    {
        outputFile = fopen(myOutputFile, "w");

        printf("\nCOST of %d = %d", i, cost[i]);
        printf("\nTRACE = %d", i);

        j=i;
        do
        {
            j=pred[j];
            printf(" %d", j);

        }
        while(j!=startnode);
    }

You can use fprintf(FILE * stream, const char * format, ... ) and pass the file handle to the function. 您可以使用fprintf(FILE * stream,const char * format,...)并将文件句柄传递给该函数。

for(i=0;i < n;i++)
    if(i!=startnode)
    {
        outputFile = fopen(myOutputFile, "a");

        fprintf(outputFile,"\nCOST of %d = %d", i, cost[i]);            
        fprintf(outputFile,"\nTRACE = %d", i);

        j=i;
        do
        {
            j=pred[j];
            fprintf(outputFile," %d", j);

        }
        while(j!=startnode);
       fclose(outputFile);
    }

Edit according to your comment: 根据您的评论进行编辑:

According to your comment update the mode you are opening the file to: fopen("asdas","a") 根据您的评论更新模式,您正在将文件fopen("asdas","a")为: fopen("asdas","a")

Try this: 尝试这个:

outputFile = fopen(myOutputFile, "a");
for(i=0;i < n;i++)
    if(i!=startnode)
    {    
        fprintf(outputFile,"\nCOST of %d = %d", i, cost[i]);            
        fprintf(outputFile,"\nTRACE = %d", i);

        j=i;
        do
        {
            j=pred[j];
            fprintf(outputFile," %d", j);

        }
        while(j!=startnode);
    }

Try this: 尝试这个:

freopen(myOutputFile, "a+",stdout);  //Redirect the standard output to file, "a+" - is for appending info if the file is has data before it is openned
for(i=0;i < n;i++)
{        
    if(i!=startnode)
    {
        printf("\nCOST of %d = %d", i, cost[i]);            
        printf("\nTRACE = %d", i);

        j=i;
        do{
            j=pred[j];
            printf(" %d", j);

        }while(j!=startnode);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM