简体   繁体   English

文件格式导致程序崩溃

[英]program crashes due to file format

i was trying this problem from usaco. 我正在从usaco尝试这个问题。 when i use txt file while using file the program is working fine. 当我在使用文件时使用txt文件时,程序运行正常。 but when for the submission requirement i change the format to beads.in and beads.out the program crashes. 但是,对于提交要求,我将格式更改为beads.in和beads.out时程序崩溃。 what;s the problem? 有什么问题? here's my code: 这是我的代码:

#include <stdio.h>
#include<string.h>
main () {
    FILE *fin  = fopen ("beads.in", "r");
    FILE *fout = fopen ("beads.out", "w");
    int n;
    char str[400];
    char now,rev_now;
    int pos,forward,reverse,sum,max=0,i,j,k;
    fscanf(fin,"%d\n%s",&n,str);
    n--;
    for(pos=0;pos<=n;pos++){
        now=str[pos];
        if(pos==0)k=n;
        else k=pos-1;
        rev_now=str[k];
        forward=2;
        int flag1=0,flag2=0,reverse=2;

        for(i=pos,j=k;;){
            if(i==n)i=-1;
            if((str[i+1]==now||str[i+1]=='w')&&flag1==0){
                i++;
                forward++;
            }
            else{
                flag1=1;
            }
            if(j==0)j=n+1;
            if((str[j-1]==rev_now||str[j-1]=='w')&&flag2==0){
                j++;
                reverse++;
            }
            else{
                flag2=1;
            }
            if(flag1==1 && flag2==1)break;
        }
        sum=forward+reverse;
        if(max<sum){max=sum;}
    }
    fprintf(fout,"%d\n",max);
    return 0;
}

are you sure beads.in and beads.out are created already.. 您确定已经创建了beads.inbeads.out

According to man page 根据手册页

 r      Open  text  file  for  reading.  The stream is positioned at the
        beginning of the file.

 w      Truncate  file  to  zero length or create text file for writing.
        The stream is positioned at the beginning of the file.

May be beads.in is not created in prior to fopen. 可能是在fopen之前未创建beads.in It's better if you check the status of the fopen , use perror . 最好检查一下fopen的状态,使用perror

You mention that it works with a text file. 您提到它与文本文件一起使用。 I'm guessing that beads.in is not a text file, but rather a binary file. 我猜想beads.in不是文本文件,而是二进制文件。 If that is the case, then @KVD's suggestion above to use: fopen ("beads.in", "rb"); 如果是这样,则fopen ("beads.in", "rb");在上面的建议中使用: fopen ("beads.in", "rb"); and fopen ("beads.out", "wb"); fopen ("beads.out", "wb"); should work. 应该管用。 The reason the program would crash with binary input data is because you are asking fscanf to copy data into your str buffer until it encounters a newline character. 程序会因二进制输入数据而崩溃的原因是,您正在要求fscanf将数据复制到str缓冲区中,直到遇到换行符为止。 More than likely, the beads.in file has more than 400 characters which will cause a buffer overflow and start overwriting the program stack. beads.in文件很有可能超过400个字符,这将导致缓冲区溢出并开始覆盖程序堆栈。

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

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