I'm trying to print line numbers in the beginning of the lines without using fgets()
yes, it prints line number well when I input multiple files
but I want to get result like this. Can you guys help me with this?
Now result
1 I'll always remember
2 the day we kiss my lips
3
4 light as a feather
*5 #####localhost ~ $*
expect result
1 I'll always remember
2 the day we kiss my lips
3
4 light as a feather
*#####localhost ~$*
Here is my code:
#include <stdio.h>
int main(int argc, char *argv[]) {
FILE *fp;
int c, n;
n = 1;
for (int i = 1; i < argc; i++) {
if (argc < 2)
fp = stdin;
else
fp = fopen(argv[i], "r");
c = getc(fp);
printf("%d ", n);
while (c != EOF) {
putc(c, stdout);
if (c == '\n')
n++, printf("%d ", n);
c = getc(fp);
}
fclose(fp);
}
return 0;
}
Do not write printf("%d ", n); when you do not know if there is the next line. Or, otherwise, do printf("%d ", n); only on the beginning of the file and after a newline when you know there is a next char.
#include <stdbool.h> // for bool, true, false
bool previous_character_was_a_newline = true;
while ((c = getc(fp)) != EOF) {
if (previous_character_was_a_newline) {
previous_character_was_a_newline = false;
printf("%d ", n);
}
putc(c, stdout);
if (c == '\n') {
n++;
previous_character_was_a_newline = true;
}
}
Do not write code like n++, printf("%d ", n);, it will be confusing. Strongly prefer:
if (c == '\n') {
n++;
printf("%d ", n);
}
Your implementation outputs the line number before the first line and after each newline, including the one at the end of the file. This causes an extra line number to appear at the end of the file.
Let's define the output more precisely:
you want the line number at the beginning of each line, no output if no line, no line number after the last line.
do you want the line counter to reset to 1 when a new file is read? I assume no, but cat -n does.
do you want to output an extra newline at the end of a non empty file that does not end with a newline? I assume yes but cat -n does not.
Here is a modified version where the answer is no for the first question and yes for the second:
#include <stdio.h>
int output_file(FILE *fp, int line) {
int c, last = '\n';
while ((c = getc(fp)) != EOF) {
if (last == '\n') {
printf("%d\t", line++);
}
putchar(c);
last = c;
}
/* output newline at end of file if non empty and no trailing newline */
if (last != '\n') {
putchar('\n');
}
return line;
}
int main(int argc, char *argv[]) {
int n = 1;
if (argc < 2) {
n = output_file(stdin, n);
} else {
for (int i = 1; i < argc; i++) {
FILE *fp = fopen(argv[i], "r");
if (fp == NULL) {
perror(argv[i]);
} else {
n = output_file(fp, n);
fclose(fp);
}
}
}
return 0;
}
Related
I am trying to get this piece of code to read a line from a file but it's not working. I was wondering if one of you could help me. It was going to read the last 5 lines which I can configure later, but right now I am just trying to get it to read the last line.
#include <stdlib.h>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
FILE *myfile = fopen("X:\\test.txt", "r");
int x, number_of_lines = 0, count = 0, bytes = 512, end;
char str[256];
do {
x = fgetc(myfile);
if (x == '\n')
number_of_lines++;
} while (x != EOF); //EOF is 'end of file'
if (x != '\n' && number_of_lines != 0)
number_of_lines++;
printf("number of lines in test.txt = %d\n\n", number_of_lines);
for (end = count = 0; count < number_of_lines; ++count) {
if (0 == fgets(str, sizeof(str), myfile)) {
end = 1;
break;
}
}
if (!end)
printf("\nLine-%d: %s\n", number_of_lines, str);
fclose(myfile);
system("pause");
return 0;
}
Here is a simple solution where you read all lines into a circular line buffer and print the last 5 lines when the end of file has been reached:
#include <stdio.h>
int main(void) {
char lines[6][256];
size_t i = 0;
FILE *myfile = fopen("X:\\test.txt", "r");
if (myfile != NULL) {
while (fgets(lines[i % 6], sizeof(lines[i % 6]), myfile) != NULL) {
i++;
}
fclose(myfile);
for (size_t j = i < 5 ? 0 : i - 5; j < i; j++) {
fputs(lines[j % 6], stdout);
}
}
return 0;
}
Just make a for or while cycle that reads all the file(use fscanf) and when the reading gets to your desired line you save it to a var.
I'm writing program that counts words in C, I know I can do this simply with fscanf. But I'm using getc.
I have file like this:
One two three four five.
I'm reading chars in while loop and breaking point is when I reach terminal null.
Will c = fgetc(input); or c = getc(input); set c = '\0'; after One_ and after two_ etc.?
When a return value of a function like getc() is EOF which is -1,then you have reached the end of file.try this code to count words:
#include <stdio.h>
int WordCount(FILE *file);
int main(void)
{
FILE *file;
if(fopen_s(&file,"file.txt","r")) {
return 1;
}
int n = WordCount(file);
printf("number of words is %d\n", n);
fclose(file);
return 0;
}
int WordCount(FILE *file)
{
bool init = 0;
int count = 0, c;
while((c = getc(file)) != EOF)
{
if(c != ' ' && c != '\n' && c != '\t') {
init = 1;
}
else {
if(init) {
count++;
init = 0;
}
}
}
if(init)
return (count + 1);
else
return count;
}
So I want to write a program which would print out a text line that contains a certain word from a file. e.g. if I was looking for a word 'linux' it would print out
2 computers called linux00, linux01 and linux02. 5 manager,"
said linux00. "Hello linux00," said 7 here to see us?" said
linux01. "Well," said the 10 linux02. "You're all going to be
unplugged," said 12 goooooooooooo..." said linux00.
from a story.txt:
Once upon a time, there were three little computers called
linux00, linux01 and linux02. One day, the nice computer manager
came into the Linux Laboratory. "Hello nice computer manager,"
said linux00. "Hello linux00," said the nice computer manager.
"What brings you here to see us?" said linux01. "Well," said the
nice computer manager, "I've got bad news and I've got good
news." "What's the bad news?" said linux02. "You're all going to be
unplugged," said the nice computer manager. "What's the
goooooooooooo..." said linux00.
Here's my code:
#include<stdio.h>
#include <stdlib.h>
#define ARR_LEN 100
int getLine(FILE * fin,char a[],int n)
{
int find = contains("linux", 5, a, ARR_LEN);
int count;
int i;
i = 0;
char c = getc(fin);
while(c != '\n')
{
a[i] = c;
// printf ("%c", a[i]);
//i = 0;
if (a[i] == EOF){
return EOF;
}
if (find == 1)
{
printf("%c", c);
c = getc(fin);
}
i = i + 1;
}
if(a[i]=='\n')
{
if ((i - 1) > ARR_LEN) {
printf("warning msg: length is over array bounds\n");
}
// printf("length of line is: %d\n", i - 1);
//printf("%c", a[i]);
i = i + 1;
//printf("\n");
return i - 1;
}
}
int contains(char target[], int m, char source[], int n) {
int flag = 0; // the source originally does not contain the target
int i;
for(i = 0; i < n; i++) { // go through each character of the source string
int targetIndex = 0;
int j;
/*check if the preceding characters of the source string are a substring
that matches the target string*/
for(j = i; j < n && targetIndex < m; j++) {
if(target[targetIndex] == source[j]) {
targetIndex += 1;
if(targetIndex == m) { // the 'target' has been fully found
flag = 1;
break;
}
}
else
{
break;
}
}
if(flag == 1) // 'target' is already found, no need to search further
{
break;
}
}
return flag;
}
main(int argc,char ** argv)
{
setbuf(stdout,NULL);
char a[ARR_LEN];
FILE * fin;
if(argc<2){
printf("wrong number of arguments\n");
exit(0);
}
fin = fopen(argv[1], "r");
if (fin == NULL) {
printf("Cannot open %s\n", fin);
exit(0);
}
int t = 0;
int j = 0;
int find = contains("linux", 5, a, ARR_LEN);
while (j != EOF)
{
t = t + 1;
printf("%d ", t);
j = getLine(fin,a,ARR_LEN);
printf("\n");
}
fclose(fin);
}
The getLine function is alright and it prints out a text with a line number in front all good. But the problem is with this
if (find == 1)
{
printf("%c", c);
c = getc(fin);
}
part, where I want the program to only print out the line if "contains" finds a match in that line.
Thanks for any help & sorry for a long post!!
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char sentence[500];
char word[10] = "linux";
FILE* fp1 = fopen("strstr.txt","r");
if(fp1 == NULL)
{
printf("Failed to open file\n");
return 1;
}
while((fscanf(fp1,"%[^\n]\n",sentence)>0))
{
if(strstr(sentence,word)!=NULL)
printf("%s\n\n",sentence);
}
}
I am new to C and I am having trouble with this program. I'm trying to read text from stdin until EOF and write to standard output the number of words read and the number of lines of input. A word being defined as any string of characters except whitespace. My problems are (1) when the program has to read the last word in a line, it reads an end of line and not a whitespace so it does not add the word, and (2) when the program has to read multiple lines of input. Do I need to do a nested for loop with fgets to read until != "\n"? I am not sure on that one. Here is what I have right now:
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main ()
{
char previousLetter;
char line[500];
int numberOfWords, numberOfLines, length, i;
while (fgets (line, 500, stdin) != NULL)
{
length = strlen(line);
if (length > 0)
{
previousLetter = line[0];
}
for (i=0; i <= length; i++)
{
if(line[i] == ' ' && previousLetter != ' ')
{
numberOfWords++;
}
previousLetter = line[i];
}
numberOfLines++;
}
printf ("\n");
printf ("%d", numberOfWords);
printf (" %d", (numberOfWords / numberOfLines));
}
fgets() stores the line ending character, so you can check that as well to mark an end of word
Your code already reads multiple lines of input
Why use fgets at all?
#include<ctype.h>
#include<stdio.h>
int main(void)
{
int c;
enum {in, out} state = out;
int line_count = 0;
int word_count = 0;
while( ( c = fgetc(stdin)) != EOF ) {
if(isspace(c)) {
state = out;
} else {
if( state == out )
word_count += 1;
state = in;
}
if( c == '\n')
line_count += 1;
}
printf( "words: %d\n", word_count );
printf( "lines: %d\n", line_count );
return 0;
}
So I have a program that takes a file and reads in character by character and prints the character and the hexadecimal equivalent.
`
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *labFile;
char buf;
labFile = fopen("lab1.dat", "r");
if (labFile == NULL) perror("Error opening file\n");
while( (buf = fgetc(labFile) ) != EOF){
if(("%x", buf)< 16){
printf("%c 0%x\n", buf, buf);
}
else
printf("%c %x\n", buf, buf);
}
fclose(labFile);
return 0;
}
`
The program works the way I need it to except for one thing. I need the program to output the hex number on top then the character directly underneath the number and this process needs to continue horizontally.
Any help would be greatly appreciated!
You should output the characters as hex first, and save each read in character that has been printed until you run out of columns on your screen. You can then move to the next line, and print out the characters that were saved underneath the hex output.
You can simplify your logic to format your hex output into a single print statement.
When printing out the character, you need to have a plan to represent non-printable characters. In the sample program below, we handle it by printing two consecutive dots.
void print_chars (unsigned char *p, int num) {
int i;
for (i = 0; i < num; ++i) {
printf("%s%c%s",
isprint(p[i]) ? " " : ".",
isprint(p[i]) ? p[i] : '.',
(i < num-1) ? " " : "\n");
}
}
int main() {
FILE *labFile;
char buf;
int count = 0;
int num = COLUMNS/3;
char printed[num];
labFile = fopen("lab1.dat", "r");
if (labFile == NULL) perror("Error opening file\n");
while( (buf = fgetc(labFile) ) != EOF) {
printf("%s%02x", count ? " " : "", buf);
printed[count++] = buf;
if (count == num) {
count = 0;
putchar('\n');
print_chars(printed, num);
}
}
fclose(labFile);
if (count) {
putchar('\n');
print_chars(printed, count);
}
return 0;
}
The number of columns is divided by 3 since each character takes about 3 columns for output (2 hex characters, and a space). Retrieving the number of columns is system dependent, but you can just plug in 80 if you wish.
You could do something like this. ASSUMES your lines are < 100 chars long. Not safe.
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *labFile;
char buf[100];
labFile = fopen("lab1.dat", "r");
if (labFile == NULL) perror("Error opening file\n");
while(fgets(buf, 100, labFile)) {
if(rindex(buf, '\n')) *rindex(buf, '\n') = 0;
int i, n = strlen(buf);
for(i = 0; i != n; i++) {
printf("0%x ", buf[i]);
}
printf("\n");
for(i = 0; i != n; i++) {
printf("%c ", buf[i]);
}
printf("\n");
}
fclose(labFile);
return 0;
}