C代码在Linux编译器中不起作用
下面的代码是关于C中的文件操作的C代码在Linux编译器中不起作用,c,linux,dev-c++,C,Linux,Dev C++,下面的代码是关于C中的文件操作的 FILE* file = fopen("txt", "r"); char line[256]; char a[10][14]; char getIndex[2]; char firstIndex[2]; char secondIndex[2]; int firstIndexNum; int secondIndexNum; printf("Please enter number:"); fgets (getIndex, 100, stdin); strcpy(
FILE* file = fopen("txt", "r");
char line[256];
char a[10][14];
char getIndex[2];
char firstIndex[2];
char secondIndex[2];
int firstIndexNum;
int secondIndexNum;
printf("Please enter number:");
fgets (getIndex, 100, stdin);
strcpy(firstIndex,getIndex);
firstIndexNum = atoi(firstIndex);
secondIndexNum = firstIndexNum + 1;
sprintf(secondIndex, "%d", secondIndexNum);
int i = 0;
while (fgets(line, sizeof(line), file)) {
strcpy(a[i],line);
i++;
}
int sizeArray = sizeof(a) / sizeof(a[0]);
for(int i=1;i<=sizeArray;i++){
if(strstr(a[i-1], firstIndex) != NULL){
while(strstr(a[i], secondIndex) == NULL){
printf("%s",a[i]);
i++;
}
}
}
fclose(file);
return 0;
第一个程序读取文件并将其存储到数组,然后该程序向用户询问您希望从文件中获取哪个问题。如果用户输入,“2”程序从文件中获取第二个问题(获取文件中2到3个数字之间的所有字符),并打印到屏幕上
<>我在Windows中用DeV C++编译器编写了这个代码。它在DeV C++中工作。p>
但是当我在Linux终端中尝试这段代码时,代码会询问用户一个整数,但它不会将结果从文件打印到屏幕上。它不会给出任何错误,程序将关闭
FILE* file = fopen("txt", "r");
char line[256];
char a[10][14];
char getIndex[2];
char firstIndex[2];
char secondIndex[2];
int firstIndexNum;
int secondIndexNum;
printf("Please enter number:");
fgets (getIndex, 100, stdin);
strcpy(firstIndex,getIndex);
firstIndexNum = atoi(firstIndex);
secondIndexNum = firstIndexNum + 1;
sprintf(secondIndex, "%d", secondIndexNum);
int i = 0;
while (fgets(line, sizeof(line), file)) {
strcpy(a[i],line);
i++;
}
int sizeArray = sizeof(a) / sizeof(a[0]);
for(int i=1;i<=sizeArray;i++){
if(strstr(a[i-1], firstIndex) != NULL){
while(strstr(a[i], secondIndex) == NULL){
printf("%s",a[i]);
i++;
}
}
}
fclose(file);
return 0;
FILE*FILE=fopen(“txt”、“r”);
字符行[256];
字符a[10][14];
char-getIndex[2];
char-firstIndex[2];
字符二次索引[2];
int firstIndexNum;
int secondIndexNum;
printf(“请输入号码:”);
fgets(getIndex,100,标准数据);
strcpy(firstIndex,getIndex);
firstIndexNum=atoi(firstIndex);
secondIndexNum=firstIndexNum+1;
sprintf(secondIndex,“%d”,secondIndexNum);
int i=0;
while(fgets(行、sizeof(行)、文件)){
strcpy(a[i],行);
i++;
}
int sizeArray=sizeof(a)/sizeof(a[0]);
对于(int i=1;i您需要将带有CR/LF行结尾的文件'poems.txt'转换为Unix行结尾。这可以通过'tr'命令完成
tr -d '\r' < input.file > output.file
tr-d'\r'output.file
Linux上的程序流程如何?@user9134929:值得注意的是,这足以“解决”您的问题。然而,注释中指出的问题意味着您的代码充其量是难以置信的脆弱-对于大多数目的来说,除非您也修复这些问题,否则它仍然非常脆弱。没有问题,但您理解为什么要转换吗解决了你的问题?我完全同意Jonathan的意见,该源代码中几乎每一行都潜伏着分段错误。如果@user9134929在问题(前十行)中添加'poems.txt'示例,并改进源代码(添加main()和stdio.h),这对所有人都是有益的.dos2unix
可能比运行shell命令简单一些。该实用程序不需要两个不同的文件来操作(就像tr
一样)。