简体   繁体   English

在Linux下使用C读取txt。 我应该把txt文件放在哪里?

[英]reading a txt using C under linux. Where should I put the txt file?

I am trying to read from a txt file using C under Linux. 我正在尝试在Linux下使用C从txt文件读取。 FILE*fp=fopen("test.txt","r"); FILE * fp = fopen(“ test.txt”,“ r”); I have the above code, but it's telling me "segmentation fault(core dumped)". 我有上面的代码,但它告诉我“分段错误(核心已转储)”。 Is this because I don't have my txt under the correct directory? 这是因为我的txt不在正确的目录下吗?

int main(int argc, char*args[])
{
//printf("%d\n", argc);
int i;
for(i=0;i<argc;i++)
{
printf("%s ", args[i]);
}
int numProcesses=10;
int memorySize=atoi(args[1]);
int pageSize=atoi(args[2]);
int alloAlg=atoi(args[3]);
int evicAlg=atoi(args[4]);
int globLoc=atoi(args[5]);
int peroid=atoi(args[6]);

FILE*fp;
fp=fopen("Desktop/plist.txt","r");
char buff[1000];
//fgets(buff,100,fp);
//printf("%s",buff);
}

When you open a file without a path, it is assumed that file rests in the current directory. 当您打开不带路径的文件时,假定该文件位于当前目录中。 As for your segmentation fault -- you should be testing the FILE pointer against NULL before trying to read/write from it anyway. 至于分段错误-无论如何,在尝试从FILE指针读取/写入之前,应针对NULL测试FILE指针。

将文本文件放在创建可执行文件的文件夹中。

You are no getting segmentation fault because of FILE *fp = fopen("test.txt","r") command. 您不会因为FILE *fp = fopen("test.txt","r")命令而遇到分段错误。 (If this is what you are thinking) (如果这是您的想法)

If a file that you are trying to open by fopen() does not exist. 如果您尝试通过fopen()打开的文件不存在。 fopen() will simply return NULL in that case. 在这种情况下, fopen()将仅返回NULL。

You are getting segmentation fault, most probably, because you are trying to read something using the file pointer fp . 您很可能会遇到分段错误,因为您正在尝试使用文件指针fp读取某些内容。 For ex: you are doing something like char ch = fgetc(fp) . 例如:您正在执行类似char ch = fgetc(fp)

To avoid this, you can always check the value returned by fopen() . 为了避免这种情况,您始终可以检查fopen()返回的值。 NULL is return by fopen() if it cannot open the file. 如果fopen()无法打开文件,则返回NULL。

So you could do something like this: 因此,您可以执行以下操作:

FILE *fp = fopen("text.txt","r");
if(fp == NULL)
{
    //Your code to handle this case where file was not opened by fopen
}
else
{
    //Do what you wanted to do with your file
}

So, answer to your question is both yes and no. 因此,回答您的问题既是肯定的又是否。

Yes: because the segmentation fault is because fp contains NULL because your txt file is not in your directory. 是:因为分段错误是因为fp包含NULL,因为您的txt文件不在您的目录中。

No: because the segmentation fault is actually because you are trying to access memory that you are not supposed to (), and not because the txt file is not present in directory, however with a note that, the root cause for it is that your file was not present in the directory. 否:因为分段错误实际上是因为您试图访问您不应该访问的内存(),而不是因为txt文件不存在于目录中,但是请注意,其根本原因是您的目录中不存在该文件。

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

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