The code is running well, it's just that I feel there are still many mistakes and give me a little direction to improve in the future. I want to learn how to maintain the code properly.
fix the code as it should!
Data.txt
[1] Line numbers 1.
[2] Line numbers 2.
[3] Line numbers 3.
[4] Line numbers 4.
[5] Line numbers 5.
[6] Line numbers 6.
My code:
#include <stdio.h>
#include <stdlib.h>
int getLengthFile(char *namafile)
{
FILE *fptr;
int n =0;
fptr = fopen(namafile, "r");
if(fptr != NULL){
char c;
while((c = getc(fptr)) != EOF) {
++n;
}
fclose(fptr);
}
return n;
}
int main(){
FILE *fptr;
int i;
fptr = fopen("Data.txt","r");
if(fptr != NULL){
printf("Succes reads file!\n");
if(getLengthFile("Data.txt")>0){
char strLine[225];
while(fgets(strLine,225,fptr) != NULL){
printf("%s",strLine);
}
}else{
printf("File is empty!\n");
}
fclose(fptr);
}else{
printf("Error reads file!\n");
}
return 0;
}
Here is a more or less fixed version of the code presented in the first edition of the question, where the getLengthFile() function was not present. In my opinion, that function does not provide useful functionality. If you must report that the file contained no data, you could do so by counting the number of times fgets() returns any data — if it returns any data, the file was not empty.
#include <stdio.h>
int main(void)
{
const char filename[] = "Data.txt";
FILE *fptr = fopen(filename, "r");
if (fptr == NULL)
{
fprintf(stderr, "Error opening file %s for reading!\n", filename);
return 1;
}
printf("Success opening file %s for reading\n", filename);
char strLine[225];
while (fgets(strLine, sizeof(strLine), fptr) != NULL)
printf("%s", strLine);
fclose(fptr);
return 0;
}
When there is no file Data.txt, example output is:
Error opening file Data.txt for reading!
When there's a file containing one short line of data, example output is:
Success opening file Data.txt for reading
data from the file Data.txt
I also tested it on a file with longer lines, including lines with as many as 380 characters, and the output from the program was the same as the input except for the line saying 'Success opening file Data.txt for reading'.
Related
Hello I am writing a program that reads the contents of a binary file and prints them to the screen.
#include <stdio.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr;
char filename[100];
printf("Enter the filename to open \n");
scanf("%s", filename);
// Open file
fptr = fopen(filename, "rb");
if (fptr == NULL)
{
printf("Cannot open file \n");
exit(0);
}
// Read contents from file
fseek(fptr,0L,SEEK_END);
int fsize = ftell(fptr);
fseek(fptr,0L,SEEK_SET);
unsigned char *c = malloc(fsize);
fread(c,fsize,1,fptr);
fclose(fptr);
printf("%s",c);
return 0;
}
but it does not print anything.Can someone explain me why and how should I fix this problem.
What you have attempted is not at all what you wanted to achieve.
Remember printf() formats the data it prints. To be printed properly with the %s formatting, the binary data values must be ASCII values but , of course, they are not.
You should probably attempt to printf() with %d.
I'm trying to read a text file that will contain two lines, something like this:
18,3,4,c;19,3,5,D
19100,18,18;19102,3,2
and i want to store the first line in a string called Students and the second one into another string called Courses.
I have wrote this code but it stores one line only and i can't get it to work with the second line
FILE *fptr;
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
fscanf(fptr, "%[^\n]", Students);
fclose(fptr);
Can anyone help me with that? I'm a newbie to c and i can't get how to do so, Thank you in advance.
FILE *fptr;
char buffer[255] = {'\0'};
if ((fptr = fopen("program.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
fgets(Students, sizeof(Students), fptr);
fgets(Courses, sizeof(Courses), fptr);
fclose(fptr);
This line fgets(Students, sizeof(Students), fptr); will start reading from the begginning of the file and store the first line to Students char array & then fgets(Courses, sizeof(Courses), fptr); will read the second line and store it into Courses char array.
Make sure that the size of Students & Courses is large enough to accommodate each line into them.
You may try fscanf() for the problem:
#include <stdio.h>
int main(void) {
char Students[100], Courses[100];
FILE *fp = fopen("program.txt", "r");
if (!fp) {
printf("File wasn't opened.\n");
return -1;
}
fscanf(fp, "%s \n", Students);
fscanf(fp, "%s", Courses);
printf("%s\n", Students);
printf("%s\n", Courses);
fclose(fp);
return 0;
}
My program.txt contains:
John_Doe
Mathematics
Sample Output
John_Doe // Students
Mathematics // Courses
Use something like:
fscanf(fptr, "%[^\n]\n%[^\n]]\n", Students,Courses);
Where you tell scanf() to read up to a new-line, read and discard the new line, then do it again.
This is my code which I have written so far
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // For exit()
int main()
{
FILE *fptr1, *fptr2;
char filename[100], c;
char quit[4] = "exit";
// char *filearray[100];
char filearray[100][14];
FILE **originalfilearray;
int counter = 0;
//Copy part
while(1){
printf("Enter the filename to open for reading \n");
scanf("%s", filename);
fptr1 = fopen(filename, "r");
if (fptr1 == NULL)
{
break;
printf("Cannot open file %s \n", filename);
exit(0);
}
strcpy(filearray[counter], filename);
originalfilearray[counter] = fptr1;
counter+=1;
}
//Paste part
for (int i = 0; i < counter; i++)
{
printf("Enter the filename to open for writing for file %s\n", filearray[i]);
scanf("%s", filename);
fptr2 = fopen(filename, "w");
// Read contents from file
c = fgetc(fptr2);
while (c != EOF)
{
fputc(c, fptr2);
c = fgetc(originalfilearray[i]);
}
printf("\nContents copied to %s\n", filename);
}
}
The problem occurs when I run the paste code the file is created but no content is pasted.
I have already tried reading many post regarding array of pointers of file. Some suggested to create originalfilearray variable with a single pointer some with double.
The major problem I guess is with the copy part.
Can someone please help me with the part where I need to copy the data of multiple files in the originalfilearray variable
Thank You
Apart from not allocating memory for originalfilearray, which other user explained, here are some things you are doing wrong
In
c = fgetc(fptr2);
You are trying to get character from an empty file you just opened in
fptr2 = fopen(filename, "w");
what you should be doing is starting a file pointer fptr and opening
FILE *fptr=fopen(filearray[i], "r");
and then copying content into it with
while ((c = fgetc(fptr))!= EOF)
{
fputc(c, fptr2);
}
I want to write a code to extract todo task list from a code file.It's basically scanning a code file and detecting lines that include "TODO" string and then writing those lines into a text file.
So far my my code is like this:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
FILE* f;
char line[200];
f = fopen("someFile.c", "r");
char c;
char str;
while(!feof(f)){
fgets(line,sizeof(line),f);
if(strstr(line, "TODO") != NULL)//Extracts every line with TODO
{
c=fgetc(f);//c = lines with TODO
}
}
fclose(f);
f= fopen("todoListFile.txt","w");
while(!feof(f))
{
fputs(c,f);//Writing the content of the c in to the text file.
}
fclose(f);
return 0;
}
When I run this code it crashes after 1-2 seconds.
My mistake is probably at the second part which is getting those "TODO" lines and writing down those to the text lines. But I'm pretty stuck at that part and don't know what to do.
Note: Content of someFile.c is basically some comment lines with "// TODO :"
The specification pretty much indicates that you have to open two files, one for reading, one for writing. As you read a line from the input file, if that line contains TODO, you need to write that line to the output file. That leads to the straight-forward code:
#include <stdio.h>
#include <string.h>
int main(void)
{
char file1[] = "someFile.c";
char file2[] = "todoListFile.txt";
FILE *fp1 = fopen(file1, "r");
if (fp1 == NULL)
{
fprintf(stderr, "Failed to open file %s for reading\n", file1);
return 1;
}
FILE *fp2 = fopen(file2, "w");
if (fp2 == NULL)
{
fprintf(stderr, "Failed to open file %s for writing\n", file2);
return 1;
}
char line[200];
while (fgets(line, sizeof(line), fp1) != 0)
{
if (strstr(line, "TODO") != NULL)
fputs(line, fp2);
}
fclose(fp1);
fclose(fp2);
return 0;
}
Note that it checks that the files were opened successfully, and reports the file name if it failed, and exits with a non-zero status (you could add <stdlib.h> and use EXIT_FAILURE if you prefer).
When run on (a copy of) its own source, it leaves the todoListFile.txt containing one line:
if (strstr(line, "TODO") != NULL)
Simple modifications of the program would:
Write to standard output instead a fixed name file.
Take command line arguments and process all the input files named.
Read standard input if no input files are named.
Increase the line length. 200 is better than 80, but lines can be longer than that. I tend to use 4096 as a line length unless there's a reason to allow longer lines.
I want to check if there are any duplicates in a .txt file. I've wrote a code but it's not running. I'm not sure about opening the norep.txt file in "a+" mode. The idea is to put the first word of my text in the norep.txt file, then compare every word in the text.txt with the words in norep.txt and copy only the words I need in the file.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fd;
FILE *ft;
char aux[30];
char aux1[30];
int len;
fd = fopen("c:\\text.txt", "r");
if (fd == NULL) {
puts("Error");
}
ft = fopen("c:\\norep.txt", "a+");
if (ft == NULL) {
puts("Error");
}
fscanf(fd, "%s", aux);
fprintf(ft, "%s", aux);
rewind(fd);
rewind(ft);
while (!feof(fd)) {
fscanf(fd, "%s", aux);
while (!feof(ft)) {
fscanf(ft, "%s", aux1);
len = strcmp(aux, aux1);
if (len != 0) {
fprintf(ft, "%s", aux);
}
}
rewind(ft);
}
return 0;
}
You should flush the output file before you rewind it.
fflush - flush a stream or fflush
Of course, this will not fix your problem because:
Note below that the manual says that reposition operations are ignored so that your attempt to read will always find the end of file.
append: Open file for output at the end of a file. Output operations
always write data at the end of the file, expanding it. Repositioning
operations (fseek, fsetpos, rewind) are ignored. The file is created
if it does not exist.
What you should probably do is create an internal memory table that keeps all the unique entries and write it out to a new file after all processing is done. As you read the fd file, check the list and add a new entry if it is not already in the list. Then after you have finished processing fd, then and only then write out your list. Of course, this may be too big depending on the size of your data file.
You could append each unique entry to the output file as you go. but you would need to have some method of checking the previous entries without trying to read the output file.
The usual way to go about this is to read the input file word for word, store the necessary information in some way and then, after you have read all information from the file, write the desired output to the output file.
A rough skeleton of that approach might look like this:
int main()
{
const char *infile = "text.txt";
const char *outfile = "norep.txt";
FILE *in;
FILE *out;
char word[30];
// (1) Read all words
in = fopen(infile, "r"); // .. and enforce success
while (fscanf(in, "%29s", word) == 1) {
// store word somewhere
}
fclose(in);
// (2) Determine unique words somehow
// (3) Write out unique words
out = fopen(outfile, "w"); // .. and enforce success
for (i = 0; i < nunique; i++) {
fprintf(out, "%s\n", unique[i]);
}
fclose(out);
return 0;
}
The actual algorithm to fin the unique words is missing from this incomplete skeleton code.
If you really want to test the words in a file for uniqueness without using additional memory beyond the current word, you can open the input file twice, with independent file pointers. Then you can write a loop like so:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main()
{
const char *infile = "text.txt";
const char *outfile = "norep.txt";
FILE *in1;
FILE *in2;
FILE *out;
char word1[30];
char word2[30];
in1 = fopen(infile, "r");
in2 = fopen(infile, "r");
out = fopen(outfile, "w");
if (in1 == NULL || in2 == NULL || out == NULL) {
fprintf(stderr, "Could not open all required files.\n");
exit(1);
}
while (fscanf(in1, "%29s", word1) == 1) {
int count = 0;
while (fscanf(in2, "%29s", word2) == 1) {
if (strcmp(word1, word2) == 0) count++;
if (count > 1) break;
}
if (count == 1) fprintf(out, "%s\n", word1);
rewind(in2);
}
fclose(in1);
fclose(in2);
fclose(out);
return 0;
}
This will, of course, re-read the file as often as there are words in the file. Not a good approach to find the unique words in Moby-Dick. I recommend that you look into the memory-based approach.