简体   繁体   English

C fprintf写多行到文件?

[英]C fprintf writing multiple lines to file?

I have school project in Linux and I need to create a user defined text file which has 1000 random numbers between 100-999. 我在Linux上有一个学校项目,我需要创建一个用户定义的文本文件,该文件在100-999之间具有1000个随机数。

I managed to create user defined file by using array and my code has no errors but when I run it I only have one number in my file but I want to have 1000 numbers I use \\n but its not working please help me ? 我设法使用数组创建了用户定义的文件,并且我的代码没有错误,但是当我运行它时,我的文件中只有一个数字,但是我想使用1000个数字,我使用\\ n但它不起作用,请帮帮我吗?

#include<stdio.h>
#define MAX 100

int main()
{
    FILE *fp;
    char dosya[MAX];
    printf("\nLütfen dosya adı giriniz:");
    scanf("%s",dosya);
    fp=fopen(dosya,"w");
    int i;
    for (i=0;i<1000;i++);
    {

        int sayi;

        sayi=rand()%999-100;
        fprintf(fp,"\n");
        fprintf(fp,"%d\n",sayi);
        fprintf(fp,"\n");
    }
    fclose(fp);
    return 0;
}

When I run this in my file there is only one number so I think it keeps writing on the same line for 1000 times (but there is /n) where is the rest I checked the for loop and its working please help me ? 当我在文件中运行此文件时,只有一个数字,因此我认为它在同一行上写了1000次(但是/ n),我检查了for循环的其余部分在哪里,它的工作原理请帮助我?

Remove semicolon after for loop. for循环后删除分号。

When you execute your code all after all 1000 iterations only one time your block after for loop executes. 当您在全部1000次迭代后全部执行代码时,仅一次执行for循环之后的代码块。

for (i=0;i<1000;i++);  
                    ^^   

In C, all instructions are terminated in a semicolon 在C语言中,所有指令均以分号终止

Your "for" statement has a semicolon at the end, which is interpreted as a "do nothing" instruction. 您的“ for”语句末尾有分号,这被解释为“不执行任何操作”指令。

for (i=0;i<1000;i++);  

Remove the trailing semicolon and it will work. 删除尾随的分号,它将起作用。

You are terminating the for loop just after you creating it. 创建循环后,您将终止for循环。 remove the semicolon on the line below. 删除下面一行上的分号。

for (i=0;i<1000;i++); 对于(i = 0; i <1000; i ++);

Your final code: 您的最终代码:

#include<stdio.h>
#define MAX 100

int main(){
FILE *fp;
char dosya[MAX];
printf("\nLütfen dosya adı giriniz:");
scanf("%s",dosya);
fp=fopen(dosya,"w");
int i;
for (i=0;i<1000;i++){ 
    int sayi;
    sayi=rand()%999;
    fprintf(fp,"\n");
    fprintf(fp,"%d\n",sayi);
    fprintf(fp,"\n");
}
fclose(fp);
return 0;

} }

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

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