c语言 那个输入文件放在哪里啊

我编写了一个程序,用文件编写的,没错误,但是我运行的时候,显示的是:不能打开此文件,我看应该是输入文件放的位置不对,我放在了桌面,想问,那个输入的文件应该放在哪里啊……

使用C语言的文件操作函数可以读写txt文件,如果使用相对路径,文件必须放在程序相同的文件夹内。

1、C语言标准库提供了一系列文件操作函数。文件操作函数一般以f+单词的形式来命名(f是file的简写),其声明位于stdio.h头文件当中。例如:fopen、fclose函数用于文件打开与关闭;fscanf、fgets函数用于文件读取;fprintf、fputs函数用于文件写入;ftell、fseek函数用于文件操作位置的获取与设置。

2、例程:

#include<stdio.h>
int a;
char b,c[100];
int main(){
    FILE * fp1 = fopen("input.txt", "r");//打开输入文件
    FILE * fp2 = fopen("output.txt", "w");//打开输出文件
    if (fp1==NULL || fp2==NULL) {//若打开文件失败则退出
        puts("不能打开文件!");
        rturn 0;
    }
    fscanf(fp1,"%d",&a);//从输入文件读取一个整数
    b=fgetc(fp1);//从输入文件读取一个字符
    fgets(c,100,fp1);//从输入文件读取一行字符串
    
    printf("%ld",ftell(fp1));//输出fp1指针当前位置相对于文件首的偏移字节数
    
    fputs(c,fp2);//向输出文件写入一行字符串
    fputc(b,fp2);//向输出文件写入一个字符
    fprintf(fp2,"%d",a);//向输出文件写入一个整数
    
    fclose(fp1);//关闭输入文件
    fclose(fp2);//关闭输出文件,相当于保存
    return 0;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2010-11-25
要放在本工程的目录下面,也就是说你保存C原文件的那个地方,你可以点另存为,找到那个地方。本回答被提问者采纳
第2个回答  2010-11-24
应该放在你安装软件的默认位置下,里面有个lib或者是Include文件夹,放在那就可以了本回答被网友采纳
第3个回答  2010-11-25
改成这样:
#include<stdio.h>
#include<stdlib.h>

typedef struct student
{
char name[10];
int age;
char sex;
int ID;
float GPA;
} student;

student stu1[5];

void main()
{
FILE *fp1,*fp2;
int i=0;
char tname[10],tsex;
int tage,tGPA,tID;

fp1=fopen("1.txt","r");
if(fp1==NULL)
{
printf("Fail to open the infile\n");
}
fp2=fopen("2.txt","wb");
if(fp2==NULL)
{
printf("fail to open the outfile\n");
}

while(1==1)
{
if (fscanf(fp1,"%s %d %s %d %f",
tname,&tage,&tsex,&tID,&tGPA)==EOF) break;
strcpy(stu1[i].name,tname);
stu1[i].age=tage;
stu1[i].sex=tsex;
stu1[i].ID=tID;
stu1[i].GPA=tGPA;

if(stu1[i].age>1987)
fwrite(&stu1[i],sizeof(student),1,fp2);
i++;
}
fclose(fp1);
fclose(fp2);
}
第4个回答  2010-11-25
改成这样:
#include<stdio.h>
#include<stdlib.h>

typedef struct student
{
char name[10];
int age;
char sex;
int ID;
float GPA;
} student;

student stu1[5];

void main()
{
FILE *fp1,*fp2;
int i=0;
char tname[10],tsex;
int tage,tGPA,tID;

fp1=fopen("1.txt","r");
if(fp1==NULL)
{
printf("Fail to open the infile\n");
}
fp2=fopen("2.txt","wb");
if(fp2==NULL)
{
printf("fail to open the outfile\n");
}

while(1==1)
{
if (fscanf(fp1,"%s %d %s %d %f",
tname,&tage,&tsex,&tID,&tGPA)==EOF) break;
strcpy(stu1[i].name,tname);
stu1[i].age=tage;
stu1[i].sex=tsex;
stu1[i].ID=tID;
stu1[i].GPA=tGPA;

if(stu1[i].age>1987)
fwrite(&stu1[i],sizeof(student),1,fp2);
i++;
}
fclose(fp1);
fclose(fp2);
}
希望对你有帮助
相似回答