2015-11-08 65 views
1

我已经编写了一个从用户处获取文本文件的程序。每行打印60个字符

那么它应该打印60个字符,然后在时间上开始一个新行,然而,即使它的工作原理

有些话超过该上限,然后将其切断字到一半,然后再次启动

在一条新的线上。所以我需要我的程序基本上找出

这个词是否适合60个字符的限制,所以没有单词被分割。

#include <stdio.h> 
#include <stdlib.h> 
int main(void) 
{ 
char ch, file_name[25]; 
FILE *fp; 
printf("Enter file name: \n"); 
scanf("%24s" ,file_name); 

if ((fp = fopen(file_name,"r")) == NULL){ 
    perror("This file does not exist\n"); 
    exit(EXIT_FAILURE);} 

int c, count; 

count = 0; 
while ((c = fgetc(fp)) != EOF) { 
    if (c == '\n') 
     putchar(' '); 
    else 
     putchar(c); 

    count++; 
    if (count == 60) { 
     putchar('\n'); 
     count = 0; 
    } 
} 
putchar('\n'); 
fclose(fp); 
} 
+0

无关,但你的代码有一个缓冲区溢出 – mooiamaduck

+0

“无字拆了”。好的,所以你需要写下一个字是什么。那么什么定义了一个词的开始和结束。然后,您可以识别第60个字符是否在单词内。 –

+0

..或者写下一个字不是。一个定义可能是“一个词不包含空格”。 –

回答

1

你可以扫描一个单词,如果行和单词小于60,连接它们。否则,请打印该行并将该单词复制到重新开始该过程的行。

#include <stdio.h> 
#include <string.h> 

int main(void) { 
    FILE *fp = NULL; 
    char file_name[257] = {'\0'}; 
    char line[61] = {'\0'}; 
    char word[61] = {'\0'}; 
    int out = 0; 

    printf ("Enter file name:\n"); 
    scanf (" %256[^\n]", file_name); 

    if ((fp = fopen (file_name, "r")) == NULL) { 
     printf ("could not open file\n"); 
     return 1; 
    } 

    while ((fscanf (fp, "%60s", word)) == 1) { 
     if (strlen (line) + strlen (word) + 1 <= 60) { 
      strcat (line, " "); 
      strcat (line, word); 
      out = 0; 
     } 
     else { 
      printf ("%s\n", line); 
      strcpy (line, word); 
      out = 1; 
     } 
    } 
    if (!out) { 
     printf ("%s\n", line); 
    } 

    fclose (fp); 
    return 0; 
} 
2
#include <stdio.h> 
#include <stdlib.h> 
int readWord(FILE *fp,char *buff,char *lastChar){ 
    char c; 
    int n=-1; 
    *buff=0; 
    *lastChar=0; 
    while((c= fgetc(fp))!=EOF){ 
     n++; 
     if(isspace(c)){ 
      /* 
       you may keep tabs or replace them with spaces 
      */ 
      *lastChar=c; 
      break; 
     }  
     buff[n]=c; 
     buff[n+1]=0; 
    } 
    return n; 
} 


int main(void) { 
    char ch, file_name[25]; 
    char buff[50]; 
    int pos=0; 
    FILE *fp; 
    printf("Enter file name: \n"); 
    gets(file_name); 

    if (!(fp = fopen(file_name,"r"))) { 
     perror("This file does not exist\n"); 
     exit(EXIT_FAILURE); 
    } 

    int c, count; 

    count = 0; 
    while ((pos=readWord(fp,buff,&ch))!=EOF) { 
     count+=pos+(!!ch); 
     if(count>60){ 
      printf("\n"); 
      count=pos; 
     } 

     if(ch){ 
      printf("%s%c",buff,ch); 
     }else{ 
      printf("%s",buff); 
     } 
     if(!pos){ 
      count=0; 
     } 

    } 
    putchar('\n'); 
    fclose(fp); 
    return 0; 
}