I have a text file and I wanted to extract only a specific part of it at a particular time.For that ,I used ftell() while writing to note the start and end positions and then use fseek() to jump to that particular location.
int main()
{
FILE *fp=fopen("myt","w+");
char s[80];
printf ( "\nEnter a few lines of text:\n" ) ;
while ( strlen ( gets ( s ) ) > 0 ) //user inputs random data
{ //till enter is pressed
fputs ( s, fp ) ;
fputs ( "\n", fp ) ;
}
long int a=ftell(fp);
fputs("this line is supposed to be printed only ",fp);//line to be
// displayed
fputs("\n",fp);
long int b=ftell(fp);
printf("start is %ld",a);
printf("\nend is %ld",b);
printf("here is the data...\n");
rewind(fp);
fseek(fp,a,SEEK_CUR); //move to the starting position of text to be
//displayed
char x[1000];
fgets(x,b-a,SEEK_CUR);
printf("%s",x);
return 1;
}
I tried this but face a unexpected abnormal termination of program.Please guide me as to how correctly implement my task.
You want this:
Comments starting with //// are mine
#include <stdio.h> //// include required header files
#include <string.h>
int main()
{
FILE *fp = fopen("myt", "w+");
if (fp == NULL) //// test if file has been opened sucessfully
{
printf("Can't open file\n");
return 1; //// return 1 in case of failure
}
char s[80];
printf("\nEnter a few lines of text:\n");
while (strlen(gets(s)) > 0) //user inputs random data
{ //till enter is pressed
fputs(s, fp);
fputs("\n", fp);
}
long int a = ftell(fp);
fputs("this line is supposed to be printed only ", fp);//line to be
// displayed
fputs("\n", fp);
long int b = ftell(fp);
printf("start is %ld", a);
printf("\nend is %ld", b);
printf("here is the data...\n");
rewind(fp);
fseek(fp, a, SEEK_CUR); //move to the starting position of text to be
//displayed
char x[1000];
fgets(x, sizeof(x), fp); //// the usage of fgets was totally wrong
printf("%s", x);
return 0; //// return 0 in case of success, no one
}
Disclaimer: The first part reading the strings using gets is still sloppy, you should never use gets, it's an old deprecated function. Use fgets instead.
Related
I am trying to extract and print a specific portion of text from a file at a given time.I used ftell() and fseek() to achieve this.
#include <stdio.h> //// include required header files
#include <string.h>
int main()
{
FILE *fp = fopen("myt", "w+");
if (fp == NULL) //// test if file has been opened sucessfully
{
printf("Can't open file\n");
return 1; //// return 1 in case of failure
}
char s[80];
printf("\nEnter a few lines of text:\n");
while (strlen(gets(s)) > 0) //user inputs random data
{ //till enter is pressed
fputs(s, fp);
fputs("\n", fp);
}
long int a = ftell(fp);
fputs("this line is supposed to be printed only ", fp);//line to be
// displayed
fputs("\n", fp);
fputs("this line is also to be printed\n",fp); //line to be
//displayed
fputs("\n",fp);
long int b = ftell(fp);
fputs("this is scrap line",fp);
fputs("\n",fp);
rewind(fp);
fseek(fp, a, SEEK_CUR); //move to the starting position of text to be
//displayed
long int c=b-a; //no of characters to be read
char x[c];
fgets(x, sizeof(x), fp);
printf("%s", x);
fclose(fp);
return 0; //// return 0 in case of success, no one
}
I tried using this approach but the program just prints the first line.The output is as follows:
this line is supposed to be printed only
I want to print both the lines intended to be printed.Please suggest an approach.
I think your intent for the reading portion was
rewind(fp);
fseek(fp, a, SEEK_CUR); //move to the starting position of text to be
//displayed
long int c=b-a; //no of characters to be read
char x[c+1];
int used = 0;
while(ftell(fp) < b)
{
fgets(x+used, sizeof(x)-used, fp);
used = strlen(x);
}
printf("%s", x);
Notes:
I added +1 to the allocation of your buffer x because fgets adds
null termination.
I'm not 100% sure you don't want fflush(fp) between the writes and the reads.
I have a text file text.txt that reads (for simplicity purposes)
this is line one
this is line two
this is line three
Again for simplicity's sake, I am just trying to set the first character in each line to 'x', so my desired result would be
xhis is line one
xhis is line two
xhis is line three
So I am opening the text.txt file and trying to overwrite each line with the desired output to the same text file. In the while loop, I set the first character in each line to 'x'. I also set the variable "line" equal to one, because if its on the first line, I want to rewind to the beginning of the file in order to overwrite at the start instead of at the end of the file. Line is then incremented so it will skip the rewind for the next iteration, and should continue to overwrite the 2nd and 3rd lines. It works perfectly for the first line.
Anybody have any solutions? BTW, I have researched this extensively both on stackoverflow and other sites, and no luck. Here's my code and my output is also below:
#include <stdio.h>
#include <stdlib.h>
#define MAX 500
int main() {
char *buffer = malloc(sizeof(char) * MAX);
FILE *fp = fopen("text.txt", "r+");
int line = 1;
while (fgets(buffer, 500, fp) != NULL) {
buffer[0] = 'x';
if (line == 1) {
rewind(fp);
fprintf(fp, "%s", buffer);
}
else {
fprintf(fp, "%s", buffer);
}
line++;
}
free(buffer);
fclose(fp);
}
Output:
xhis is line one
this is line two
xhis is line two
e
x
long pos = ftell(fp);//Save the current position
while (fgets(buffer, 500, fp) != NULL) {
buffer[0] = 'x';
fseek(fp, pos, SEEK_SET);//move to beginning of line
fprintf(fp, "%s", buffer);
fflush(fp);
pos = ftell(fp);//Save the current position
}
I always suggest to use another file do this kindda solutions.
Read the line
Put x in a new file in a line and the copy the rest of the line.
Do this till you get EOF
remove the old file
rename this new file
try this out
#include<stdio.h>
#include<stdio.h>
#include<string.h>
int main()
{
char buffer[500],read[50][50];
FILE *fp=fopen("text.txt","r+");
int line =1;
while(fgets(buffer,500,fp)!=NULL){
buffer[0]='x';
printf("\n%d ",line);
puts(buffer);
strcat(read[line-1],(const char*)buffer);
line++;
}
fclose(fp);
FILE *fp1=fopen("text.txt","w");
rewind(fp1);
fprintf(fp1,"%s",read);
return 0;
}
I worked this out on windows
// file_overwrite.cpp : main project file.
// File opens and write y value to a file
// again reads same file and re-writes y value to a file
#include "stdafx.h"
using namespace System;
#include<stdio.h>
#include<stdio.h>
#include<string.h>
#include <conio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int x = 19530;
FILE *fp1 = fopen("D:\\Data\\BUFF.txt","w+");
if(fp1 == NULL)
printf("File not opening \n");
int y=x;
fprintf(fp1, "%d \n", y);
fclose(fp1);
printf("\n file -> open -> write y value and close");
freopen("D:\\Data\\BUFF.txt", "w", fp1);
rewind(fp1);
y=100;
fprintf(fp1, "%d \n", y);
printf("\n file -> Reopen -> rewind write y values and close");
fclose(fp1);
getch();
return 0;
}
// overwrite_file.cpp
// File opens and write y value to a file
// again reads same file and re-writes y value to a file
#include "stdafx.h"
using namespace System;
#include<stdio.h>
#include<stdio.h>
#include<string.h> //Include appropriate headers
#include <conio.h>
#include<stdlib.h>
int main(int argc, char *argv[])
{
int x = 19530; // Give any value in the limit
FILE *fp1 = fopen("D:\\Data\\BUFF.txt","w+"); // open file to write
if(fp1 == NULL) // if the file pointer encounters a null, it may not open neither overwrite
printf("File not opening \n");
int y=x;
fprintf(fp1, "%d \n", y); //print y
fclose(fp1);
printf("\n file -> open -> write y value and close"); // close the file after writing the value of y
freopen("D:\\Data\\BUFF.txt", "w", fp1); //reopen and rewind file
rewind(fp1);
y=100; // this value of y given within the limits gets printed on the .exe console
fprintf(fp1, "%d \n", y);
printf("\n file -> Reopen -> rewind write y values and close"); // rewind write values and close
fclose(fp1);
getch();
return 0;
}
How i can make a new line at the end of a file to fprintf() user inputed text?
My code right now is this:
#include <stdio.h>
#include <stdlib.h>
int main()
{
int lines;
int number;
FILE *fp;
printf("Insert random number: ");
scanf("%d", &number);
fp = fopen("textfile.txt", "r");
char ch;
while((ch=fgetc(fp))!=EOF)
{
if (ch=='\n') {
lines++;
}
}
fclose(fp);
fopen("textfile.txt", "ab");
fseek(fp, lines, SEEK_SET);
fprintf(fp,"%d", number);
fclose(fp);
}
You just need to add a '\n' to the fprintf() like this
fprintf(fp,"\n%d", number)
/* ^ */
but you also need a lot of error checking, for instance fopen() returns NULL when it fails to open the file.
Your code is actually very broken, you count the lines in the file opened with "r", i.e. for reading, then you call fopen() with "ab" but discard the return value, you then fseek() the number of lines, and fseek() is for the number of characters not lines, then you write to the closed fp pointer, because
fopen("textfile.txt", "ab"); /* you don't assign the return value anywhere */
fseek(fp, lines, SEEK_SET); /* this is the same pointer you `fclosed()' */
/* ^ this will not seek to the end of the file */
fprintf(fp,"%d", number); /* here `fp' is still invalid */
Test this
#include <stdio.h>
#include <stdlib.h>
int main()
{
FILE *file;
const char *filename = "textfile.txt";
printf("Insert a number: ");
if (scanf("%d", &number) != 1)
{
fpritnf(stderr, "invalid input, expected a number\n");
return -1;
}
file = fopen(filename, "a");
if (file == NULL)
{
fprintf(stderr, "cannot open %s for appending\n", filename);
return -1;
}
fprintf(file, "\n%d", number);
fclose(file);
return 0;
}
You don't need to fseek() if you open with "a" because new content is appended to the end of the file, you need a '\n' before the user input if there was no '\n' in the file or if you want to force the new value in a new line.
You don't need the "b" in the mode string, because you are writing text to the file, and on some platforms the file will have issues when you open it in a text editor.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
i am trying to decrypt the hex string: 0440 04b4 04d0 04d0 04dc 03a0 047c 04dc 04e8 04d0 04b0 03a4
It should once decrypted properly read hello world!
however i cannot get it to output the text. instead i get a list of integers. does anyone have any ideas as to how to fix this?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (int argc, char **argv)
{
char file_name[25];
char c; //Variable to hold current character
int sz; //Length of file therefore size of array
FILE *fp;
FILE *fw;
int flag = 1;
while (flag)
{
printf("enter the name of the file you wish to decrypt\n");
fgets(file_name, sizeof file_name, stdin); //fgets safer than gets, prevents infinite input
printf("Reading: %s.....\n", file_name); //debug print, can remove
strtok(file_name, "\n"); //fgets potentially leaves \n on file name, this removes
fp=fopen(file_name,"rt"); //file is opened
fw = fopen("revertedfile.txt", "w"); //oens write file
if( fp == NULL ) //checks if file empty/doesn't exist
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
//Following code finds length of file by seeking, then resets the file point to the start
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
printf("Length of file is: %i\n",sz); // Debug print, can delete
fseek(fp, 0L, SEEK_SET);
int data[sz]; //Init array based on file length
int i = 0; //Counter set to 0
while((c=fgetc(fp))!=EOF) //While haven't reached end of file.
{
int ic = (int)c - 200; //minus 200 to the ascii code
//printf("ASCI Code + 100 = %i\n", ic); //debug print
//Could do bit shift before adding to array, I Guess
data[i] = ic; //Add ASCII code to array at i
data[i] = data[i] >> 2; //Bit shift
//Debug print, shows what's happening
int test = data[i];
printf("%i\n", data[i]);
fprintf(fw, "%i\n", data[i]);
//printf("Added %i to the array at point %d\n", test, i);
i++; //Increment pointer for array
}
fclose(fp); //Always close file
fclose(fw); // closes write file
}
return 0;
}
This is the encryption code
printf("enter name of the file you wish to encrypt\n");
fgets(file_name, sizeof file_name, stdin); //fgets safer than gets, prevents infinite input
printf("Reading: %s.....\n", file_name); //debug print, can remove
strtok(file_name, "\n"); //fgets potentially leaves \n on file name, this removes
fp = fopen(file_name,"rt"); //file is opened
fw = fopen("output.txt", "w"); //oens write file
if( fp == NULL ) //checks if file empty/doesn't exist
{
perror("Error while opening the file.\n");
exit(EXIT_FAILURE);
}
//Following code finds length of file by seeking, then resets the file point to the start
fseek(fp, 0L, SEEK_END);
sz = ftell(fp);
printf("Length of file is: %i\n",sz); // Debug print, can delete
fseek(fp, 0L, SEEK_SET);
int data[sz]; //Init array based on file length
int i = 0; //Counter set to 0
while((c=fgetc(fp))!=EOF) //While haven't reached end of file
{
printf("Current char: %c\n",c); //Debug print
int ic = (int)c + 200; //Add 200 to the ascii code
//printf("ASCI Code + 100 = %i\n", ic); //debug print
//Could do bit shift before adding to array, I Guess
data[i] = ic; //Add ASCII code to array at i
data[i] = data[i] << 2; //Bit shift
//Debug print, shows what's happening
int test = data[i];
printf("%04x ", data[i]);
fprintf(fw, "%04x ", data[i]);
//printf("Added %i to the array at point %d\n", test, i);
i++; //Increment pointer for array
}
fclose(fp); //Always close file
fclose(fw); // closes write file
//Debug
int test2 = data[1];
printf("The new file is named output.txt");
If you want to decrypt it, you need to know how it was encrypted (well, that still might not be enough). If you just need to print the character each ASCII code represents, you just need to tell printf that by using %c instead of %i.
So i've been given an exercise to work on: Have the user input a number and the program will display the line of text associated with that line for example
Password
abcdefg
Star_wars
jedi
Weapon
Planet
long
nail
car
fast
cover
machine
My_little
Alone
Love
Ghast
Input 3: Output: Star_wars
Now i have been given a program to solve this, however it uses the function getline() , which doesn't complie on DEV C++.
#include <stdio.h>
int main(void)
{
int end = 1, bytes = 512, loop = 0, line = 0;
char *str = NULL;
FILE *fd = fopen("Student passwords.txt", "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
printf("Enter the line number to read : ");
scanf("%d", &line);
do {
getline(&str, &bytes, fd);
loop++;
if (loop == line)
end = 0;
}while(end);
printf("\nLine-%d: %s\n", line, str);
fclose(fd);
}
All i need is to know how to do this, in a simple program without the use of getline()
Thanks
Edit: I also don't want to download software to make this work
use fgets instead of getline.
#include <stdio.h>
int main(void){
int end, loop, line;
char str[512];
FILE *fd = fopen("data.txt", "r");
if (fd == NULL) {
printf("Failed to open file\n");
return -1;
}
printf("Enter the line number to read : ");
scanf("%d", &line);
for(end = loop = 0;loop<line;++loop){
if(0==fgets(str, sizeof(str), fd)){//include '\n'
end = 1;//can't input (EOF)
break;
}
}
if(!end)
printf("\nLine-%d: %s\n", line, str);
fclose(fd);
return 0;
}
You have wrote:
char *str = NULL;
and you used it without initializing:
getline(&str, &bytes, fd);
first you must initialize it:
char *str=(char*)malloc(SIZEOFSTR);
you can add this part in your program instead of your do-while loop. You will be using fscanf() whose arguments are the file pointer, specifier of data type and the variable you want to store.
printf("Enter the line number to read : ");
scanf("%d", &line);
while(line--) {
fscanf(fd,"%s",str);
}
printf("\nLine-%d:%s\n",line,str);